package cqrtplm.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hustcad.plm.pdm.common.model.dto.AttrFilterDTO;
import com.hustcad.plm.pdm.common.model.vo.BusinessObjectVO;
import com.hustcad.plm.pdm.common.model.vo.iteration.CommonIteratorVO;
import com.hustcad.plm.pdm.common.model.vo.search.ResultEntityVO;
import com.hustcad.plm.pdm.common.util.CommonUtil;
import com.hustcad.plm.pdm.file.model.dto.UploadFileDTO;
import com.hustcad.plm.pdm.folder.model.dto.filter.TySubFolderFilterQuery;
import com.hustcad.plm.pdm.folder.model.dto.filter.TyplmFolderObjDTO;
import com.hustcad.plm.pdm.folder.service.search.TyplmSubFilterObjectService;
import com.hustcad.plm.pdm.iba.model.dto.SaveObjIBADTO;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.hustcad.plm.pdm.iteration.controller.TyplmIterationController;
import com.hustcad.plm.pdm.lifestage.service.TyplmCommonLifecycleService;
import com.hustcad.plm.pdm.middle.partbom.adapter.TyplmPartBomAdapter;
import com.hustcad.plm.pdm.middle.partbom.service.TyplmPdmPartService;
import com.hustcad.plm.pdm.partbom.controller.TyplmBomController;
import com.hustcad.plm.pdm.partbom.controller.TyplmPartController;
import com.hustcad.plm.pdm.partbom.dto.*;
import com.hustcad.plm.pdm.partbom.dto.bom.BatchSaveAsDTO;
import com.hustcad.plm.pdm.partbom.dto.bom.BomSaveAsDTO;
import com.hustcad.plm.pdm.partbom.dto.bom.TyplmConvertBomInputDTO;
import com.hustcad.plm.pdm.partbom.enums.PartBomErrorCodeEnum;
import com.hustcad.plm.pdm.partbom.service.TyplmPartBomService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartUsageLinkService;
import com.hustcad.plm.pdm.partbom.service.view.TyplmViewDefService;
import com.hustcad.plm.pdm.partbom.vo.PartBomTreeByFilterVO;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.hustcad.plm.pdm.partbom.vo.PdmPartInfoVO;
import com.hustcad.plm.pdm.partbom.vo.TyPartAllVO;
import com.hustcad.plm.pdm.workflow.model.entity.UserTaskDTO;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlow;
import com.hustcad.plm.pdm.workflow.model.vo.OptionalParticipantUserTaskVO;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.dto.constraint.IbaDTO;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.entity.part.PartDO;
import com.ty.basic.entity.part.PartMasterDO;
import com.ty.basic.entity.part.PartUsageLinkDO;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.utils.ArgumentUtils;
import com.ty.basic.vo.AttributeVO;
import cqrtplm.aop.RestrictedDispatchAOP;
import cqrtplm.common.CommonService;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.constant.RTPlmConstant;
import cqrtplm.dto.*;
import cqrtplm.dto.query.BomQueryDTO;
import cqrtplm.entity.DspfMbomBomDO;
import cqrtplm.entity.DspfMbomDetailDO;
import cqrtplm.entity.RtCfgBomDO;
import cqrtplm.entity.RtCfgStatusInfoDO;
import cqrtplm.mapper.*;
import cqrtplm.service.DevOrderService;
import cqrtplm.service.QueryPartService;
import cqrtplm.service.RtCfgBomService;
import cqrtplm.service.RtSegmNumService;
import cqrtplm.service.RtZdService;
import cqrtplm.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

import static cqrtplm.constant.RTTableTypeConstant.MODEL_IBA_TYPE;
import static cqrtplm.constant.RTTableTypeConstant.STATUS_OTYPE;

/**
 * @author 博
 * @description 针对表【RT_CFG_BOM(配置管理-需求状态表-成品BOM表)】的数据库操作Service实现
 * @createDate 2025-08-25 23:24:01
 */
@Service
@Slf4j
public class RtCfgBomServiceImpl extends ServiceImpl<RtCfgBomMapper, RtCfgBomDO>
        implements RtCfgBomService {
    @Resource
    private TyplmPartBomService typlmPartBomService;
    @Resource
    private RtCfgStatusInfoMapper rtCfgStatusInfoMapper;
    @Resource
    private RtCfgBomMapper rtCfgBomMapper;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;
    @Resource
    private RtSegmNumMapper rtSegmNumMapper;
    @Resource
    private TyplmPartService typlmPartService;
    @Resource
    private TyplmPdmPartService typlmPdmPartService;
    @Resource
    private TyplmBomController typlmBomController;
    @Resource
    private TyplmViewDefService typlmViewDefService;
    @Resource
    private PlatformTransactionManager transactionManager;
    @Resource
    private TyplmWorkFlowService typlmWorkFlowService;
    @Resource
    private TyplmWorkFlowContainerService typlmWorkFlowContainerService;
    @Resource
    private DspfMbomBomMapper dspfMbomBomMapper;
    @Resource
    private DspfMbomDetailMapper dspfMbomDetailMapper;
    @Resource
    private DevOrderService devOrderService;
    @Resource
    private TyplmSubFilterObjectService typlmSubFilterObjectService;
    @Resource
    private TyplmIterationController typlmIterationController;
    @Resource
    private TyplmPartController typlmPartController;
    @Resource
    private CommonService commonService;
    @Resource
    private RTChangeMapper rtChangeMapper;
    @Resource
    private TyplmPartUsageLinkService typlmPartUsageLinkService;
    @Resource
    private RestrictedDispatchAOP restrictedDispatchAOP;
    @Resource
    private TyplmCommonLifecycleService typlmCommonLifecycleService;
    @Resource
    private RtZdService rtZdService;
    @Resource
    private RtSegmNumService rtSegmNumService;
    @Resource
    private TyplmPartBomAdapter typlmPartBomAdapter;
    @Resource
    private RTPartMapper rtPartMapper;
    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;
    @Resource
    private QueryPartService queryPartService;


    //    @Override
    //    public ResponseResult getRtCfgBuildBOMDetail(Long oid, String statuscode) throws JsonProcessingException {
    //        String jsonConfig = "{\"expandLevel\":1,\"giveUsesOccurrence\":\"N\",\"isQueryIBA\":true,\"isApplyRoot\":false,\"conditions\":[{\"view\":\"Design\",\"lifecycleStateKey\":\"\",\"expandCondition\":\"latest\",\"date\":\"\",\"baseLineOid\":\"\",\"purposeOfBom\":\"\",\"spareBom\":\"\"}],\"isFilterAttr\":false,\"attrFilterCondition\":[],\"ibaColumns\":[\"SegmNum\",\"Position\",\"ManufacturingAttr\"],\"isNestedTree\":false,\"isNeedTranEnum\":true,\"isQuerySubstitutionStatus\":false,\"isQueryConstraint\":true,\"fatherOid\":\"728607890451660800\",\"fatherOtype\":\"ty.inteplm.part.CTyPart\",\"fatherNumber\":\"18100-Z351010\",\"filterMode\":0}";
    //        if (oid == null) {
    //            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("参数为空");
    //        }
    //        //获取BOMID
    //        String bomId = getRtCfgBuildBOMDetailVoid(
    //                rtCfgStatusInfoMapper.selectStatusInfoByStatusCode(statuscode));
    //        DspfMbomDetailDO dspfMbomDetailDO = new DspfMbomDetailDO();
    //        dspfMbomDetailDO.setBomid(bomId);
    //        // 获取当前登录用户信息
    //        UserDO user = TyAccountContext.getUser();
    //            // 使用Jackson解析JSON（需要引入相关依赖）
    //            ObjectMapper objectMapper = new ObjectMapper();
    //            Map<String, Object> configMap = objectMapper.readValue(jsonConfig, Map.class);
    //
    //            ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new ExpandBomTreeByFilterDTO();
    //
    //            List<ParentBomVO> parentBomVOs = rtCfgStatusInfoMapper.selectByEBomOid(oid);
    //            //根据masterOid获取最新版本的oid
    //            String nowOid = this.getNowMasterOidByOid(parentBomVOs.get(0).getFatherOid());
    //            // 设置基础参数（从parentBomVO获取，覆盖JSON中的默认值）
    //            if (IterUtil.isNotEmpty(parentBomVOs)) {
    //                expandBomTreeByFilterDTO.setFatherOid(nowOid);
    //                expandBomTreeByFilterDTO.setFatherOtype(parentBomVOs.get(0).getFatherOtype());
    //                expandBomTreeByFilterDTO.setFatherNumber(parentBomVOs.get(0).getFatherNumber());
    //            }
    //
    //            // 设置其他参数
    //            expandBomTreeByFilterDTO.setExpandLevel(String.valueOf(configMap.get("expandLevel")));
    //            expandBomTreeByFilterDTO.setGiveUsesOccurrence((String) configMap.get("giveUsesOccurrence"));
    //            expandBomTreeByFilterDTO.setIsQueryIBA((Boolean) configMap.get("isQueryIBA"));
    //            expandBomTreeByFilterDTO.setIsApplyRoot((Boolean) configMap.get("isApplyRoot"));
    //
    //            // 设置conditions参数
    //            List<Map<String, Object>> conditions = (List<Map<String, Object>>) configMap.get("conditions");
    //            List<ChildPartsFiltersDTO> childPartsFilters = new ArrayList<>();
    //            if (conditions != null && !conditions.isEmpty()) {
    //                for (Map<String, Object> conditionMap : conditions) {
    //                    ChildPartsFiltersDTO filterDTO = new ChildPartsFiltersDTO();
    //                    filterDTO.setView((String) conditionMap.get("view"));
    //                    filterDTO.setLifecycleStateKey((String) conditionMap.get("lifecycleStateKey"));
    //                    filterDTO.setExpandCondition((String) conditionMap.get("expandCondition"));
    //                    filterDTO.setDate((String) conditionMap.get("date"));
    //                    filterDTO.setPurposeOfBom((String) conditionMap.get("purposeOfBom"));
    //                    filterDTO.setSpareBom((String) conditionMap.get("spareBom"));
    //                    childPartsFilters.add(filterDTO);
    //                }
    //            }
    //            expandBomTreeByFilterDTO.setConditions(childPartsFilters);
    //
    //            // 设置其他布尔型参数
    //            expandBomTreeByFilterDTO.setIsFilterAttr((Boolean) configMap.get("isFilterAttr"));
    //            expandBomTreeByFilterDTO.setIsNestedTree((Boolean) configMap.get("isNestedTree"));
    //            expandBomTreeByFilterDTO.setIsNeedTranEnum((Boolean) configMap.get("isNeedTranEnum"));
    //            expandBomTreeByFilterDTO.setIsQuerySubstitutionStatus((Boolean) configMap.get("isQuerySubstitutionStatus"));
    //            expandBomTreeByFilterDTO.setIsQueryConstraint((Boolean) configMap.get("isQueryConstraint"));
    //
    //            // 设置列表参数
    //            expandBomTreeByFilterDTO.setAttrFilterCondition((List<AttrFilterDTO>) configMap.get("attrFilterCondition"));
    //            expandBomTreeByFilterDTO.setIbaColumns((List<String>) configMap.get("ibaColumns"));
    //
    //            // 设置filterMode
    //            expandBomTreeByFilterDTO.setFilterMode(String.valueOf(configMap.get("filterMode")));
    //
    //            // 调用服务方法
    //            PartBomTreeByFilterVO partBomTreeByFilterVO = typlmPartBomService.expandBomTreeByFilterNew(
    //                    expandBomTreeByFilterDTO, Boolean.TRUE);
    //
    //            // 获取当前EBOM的所有下级的oid，过滤掉level为0的节点
    //            List<String> partOidList = Optional.ofNullable(partBomTreeByFilterVO)
    //                    .map(PartBomTreeByFilterVO::getPartBomTreeList)
    //                    .orElse(Collections.emptyList())
    //                    .stream()
    //                    .filter(partBomTree -> {
    //                        // 假设getLevel()返回String类型，如果是其他类型需要相应调整
    //                        String level = partBomTree.getLevel();
    //                        if ("0".equals(level)){
    //                            dspfMbomDetailDO.setParentid(partBomTree.getMasteredoid());
    //                            dspfMbomDetailDO.setPartsname(partBomTree.getMasterpartnumber());
    //                        }
    //                        return level != null && !"0".equals(level);
    //                    })
    //                    .map(PartBomTree::getPartoid)
    //                    .filter(Objects::nonNull)
    //                    .collect(Collectors.toList());
    //
    //            // 若下级oid为空，返回错误
    //            if (partOidList.isEmpty()) {
    //                throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("没有查到下级物料，请检查相关信息！");
    //            }
    //
    //            // 查询下级物料信息
    //            List<BuildEbomInfoVO> buildEbomInfoList = dspfMbomDetailMapper.batchIbaByoids(partOidList);
    //
    //            // 判空处理
    //            if (buildEbomInfoList == null || buildEbomInfoList.isEmpty()) {
    //                throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("没有查到下级物料，请检查相关信息！");
    //            }
    //
    //            // 按 partNumber 分组
    //            Map<String, List<BuildEbomInfoVO>> groupedByPartNumber = buildEbomInfoList.stream()
    //                    .collect(Collectors.groupingBy(BuildEbomInfoVO::getPartNumber));
    //
    //            List<DspfMbomDetailDO> result = new ArrayList<>();
    //            //通过传入的oid 查询父级的所有详细信息
    ////            PartDetailsVO partDetailsVO = typlmPartService.queryPartDetails(new BigInteger(nowOid), STATUS_OTYPE);
    //            RtCfgBomPartDetailVO partDetailVO = dspfMbomDetailMapper.getPartDetails(nowOid);
    //            // 遍历每个 partNumber 对应的扩展属性列表
    //            for (Map.Entry<String, List<BuildEbomInfoVO>> entry : groupedByPartNumber.entrySet()) {
    //                String partNumber = entry.getKey();
    //                List<BuildEbomInfoVO> extAttrs = entry.getValue();
    //
    //                // 获取第一个对象的基本信息（编码、名称、版本）
    //                BuildEbomInfoVO firstItem = extAttrs.get(0);
    //
    //                DspfMbomDetailDO bomDO = new DspfMbomDetailDO();
    //                bomDO.setKid(String.valueOf(snowflakeIdComponent.getInstance().nextId()));
    //                bomDO.setBomid(dspfMbomDetailDO.getBomid());
    //                bomDO.setParentid(dspfMbomDetailDO.getParentid());
    //                bomDO.setPartscode(dspfMbomDetailDO.getParentcode());
    //                bomDO.setPartscode(partNumber.substring(0,5));
    //                bomDO.setPatterncode(partNumber);
    ////                //来源信息
    ////                bomDO.setOldpartnumber(firstItem.getPartNumber());
    ////                bomDO.setOldversion(firstItem.getVerSion());
    ////                bomDO.setOldmasteroid(firstItem.getMasterOid());
    ////                bomDO.setOldotype(firstItem.getTypeOtype());
    ////                //父级信息
    ////                bomDO.setFarthermasteroid(partDetailVO.getMasteredoid());
    ////                bomDO.setFarthercode(partDetailVO.getNumberr());
    ////                bomDO.setFarthername(partDetailVO.getName());
    ////                bomDO.setFartherotype(partDetailVO.getTypeotype());
    //
    //                // 设置默认值
    //
    ////                bomDO.setDescription("");
    ////                bomDO.setSegmentnumber("");
    ////                bomDO.setAssemblyposition("");
    ////                bomDO.setAmount(0L);
    ////                bomDO.setPricing(0L);
    //                bomDO.setFCreatedate(String.valueOf(new Date()));
    //                bomDO.setFCreateuserid(String.valueOf(user.getOid()));
    //                bomDO.setFCreateusername(user != null ? user.getName() : "");
    //                String s = rtCfgStatusInfoMapper.selectInfoidByFatheroid(oid, statuscode);
    ////                if (s != null) {
    ////                     //放入需求状态表的infoid
    ////                    bomDO.setInfoid(s);
    ////                }
    //
    //
    ////                bomDO.setOid(snowflakeIdComponent.getInstance().nextId());
    //
    //                // 从扩展属性中提取特定字段的值
    //                for (BuildEbomInfoVO extAttr : extAttrs) {
    //
    //                    //内部名称
    //                    String attrName = extAttr.getExtAttrInthid();
    //                    //对应的值
    //                    String attrValue = extAttr.getExtAttrValue();
    //
    //                    // 根据扩展属性名称设置对应的字段值
    //                    //描述
    //                    if ("Description".equals(attrName)) {
    //                        bomDO.setRemarks(attrValue);
    //                    } else if ("SegmNum".equals(attrName)) {//段号
    //                        bomDO.setPositionnum(attrValue);
    //                        //装配位置（根据段号获取装配位置）
    //                        String position = rtSegmNumMapper.selectPositionById(attrValue);
    //                        bomDO.setAssemblyposition(position);
    //                    } else if ("quantity".equals(attrName)) {//数量
    //                        bomDO.setMaterialcount(attrValue);
    //                        //ROHS定价
    //                    } else if ("rohsPriceDiff".equals(attrName)) {
    ////                        bomDO.setPricing(Long.parseLong(attrValue));
    //                    }
    //                }
    //                result.add(bomDO);
    //
    //            }
    //
    //            // 批量插入
    //            int insertedCount = dspfMbomDetailMapper.batchInsert(result);
    //            if (insertedCount > 0) {
    //                return ResponseResult.success();
    //            }
    //            return ResponseResult.fail("500", "插入EBOM表失败！");
    //    }

    @Override
    public void getRtCfgBuildBOMDetailVoid(RtCfgStatusInfoDO rtCfgStatusInfoDO) throws JsonProcessingException {
        /*
         * 成品BOM搭建逻辑
         *   1.根据参考的是EBOM还是参考的成品码来拉取图号还是物料衍生码插入到BOM结构表体里面
         *   2.根据查询出的需求状态表数据插入到表头里面
         * */

        //异常信息字符串
        StringBuffer stringBuffer = new StringBuffer("");

        //根据EBOM插入表体数据
        if (StrUtil.isNotEmpty(rtCfgStatusInfoDO.getFatherOid()) && StrUtil.isEmpty(
                rtCfgStatusInfoDO.getRefermbomcode())) {
            //插入BOM表头表体数据
            this.saveByEBOMV2(rtCfgStatusInfoDO, stringBuffer);
            if (stringBuffer.length() != 0) {
                throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(stringBuffer.toString());
            }
        }

        //根据成品BOM结构拉取插入表体数据
        if (StrUtil.isNotEmpty(rtCfgStatusInfoDO.getRefermbomcode())) {
            this.saveBOMByRefermbomcode(rtCfgStatusInfoDO, stringBuffer);
        }
    }

    private void saveBOMByRefermbomcode(RtCfgStatusInfoDO rtCfgStatusInfoDO, StringBuffer stringBuffer) {
        /*
         * 参考成品码生成BOM结构逻辑
         *   1.根据参考成品码查询底层扩展属性插入bom表头表
         *   2.根据参考成品码查询底层bom结构插入bom表体表
         * */
        String bomid = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        DspfMbomBomDO dspfMbomBomDO = new DspfMbomBomDO();
        dspfMbomBomDO.setMbomcode(rtCfgStatusInfoDO.getRefermbomcode());


        PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(rtCfgStatusInfoDO.getRefermbomcode());
        PartDetailsVO partDetailsVO = typlmPartService.queryPartDetails(partDO.getOid(), partDO.getOtype());
        Map<String, List<String>> ibaAttributeMap = partDetailsVO.getIbaAttributeMap();
        if (MapUtil.isEmpty(ibaAttributeMap)) {
            stringBuffer.append("未查询到【" + partDetailsVO.getNumber() + "】扩展属性信息");
        }
        DspfMbomBomDO insertMbom = new DspfMbomBomDO(partDetailsVO, ibaAttributeMap, bomid);
        dspfMbomBomMapper.insertDspfMbomBom(insertMbom);

        // 获取BOM结构树
        PartBomTreeByFilterVO bomTreeVO = commonService.queryChildParts(
                partDO.getPartnumber(),
                partDO.getOid().toString(),
                "Design",
                Boolean.FALSE,
                null,
                "1",
                Boolean.TRUE
        );
        //子结构
        List<PartBomTree> partBomTrees = bomTreeVO.getPartBomTreeList().stream()
                .filter(partBomTree -> partBomTree != null && !"0".equals(partBomTree.getLevel()))
                .collect(Collectors.toList());
        partBomTrees.stream().forEach(i -> {
            //判断成品码下面是否是物料号和成品码不是需要抛异常让用户先处理
            if (!"物料码".equals(i.getTypeName()) && !"成品码".equals(i.getTypeName())) {
                stringBuffer.append("【" + i.getObjectNumber() + "】不是物料码和成品码,");
            }
            //判断物料码是不是已生效状态
            if (!"已生效".equals(i.getLifecycleState())) {
                stringBuffer.append("【" + i.getObjectNumber() + "】不是生效状态,");
            }
            //判断成品码下面的物料是否是检入状态，如果不是检入也要抛异常让用户处理先
            if (!"c/i".equals(i.getCheckInOrCheckOut())) {
                stringBuffer.append("【" + i.getObjectNumber() + "】不是检入状态,");
            }

            //根据物料号获取扩展属性进行插入（通过sql查询）
            List<TyIbaDataDTO> ibaList = dspfMbomBomMapper.getIbaMapByNumber(i.getObjectNumber());
            if (IterUtil.isEmpty(ibaList)) {
                stringBuffer.append("【" + i.getObjectNumber() + "】的扩展属性为空,");
            }

            Map<String, String> attributeMap = this.listChangeMap(ibaList);
            if (StrUtil.isEmpty(attributeMap.get("devCode"))) {
                stringBuffer.append("【" + i.getObjectNumber() + "】的开发令扩展属性为空,");
            }
            Map<String, List<AttributeVO>> linkMap = this.getIbaMapData(partDO.getOid(), i.getMasteredoid(),
                                                                        TableTypeConstrant.TY_PARTUSAGELINK_OTYPE);
            Map<BigInteger, Double> countMap = this.getLinkCountMap(partDO.getOid(), i.getMasteredoid());
            linkMap.forEach((k, v) -> {
                DspfMbomDetailDO dspfMbomDetailDO = this.setDspfMbomDetailDO(attributeMap, i, v);
                dspfMbomDetailDO.setMaterialcount(String.valueOf(countMap.get(k)));
                dspfMbomDetailDO.setKid(String.valueOf(snowflakeIdComponent.getInstance().nextId()));
                dspfMbomDetailDO.setBomid(bomid);
                dspfMbomDetailDO.setOtype(this.getOtypeByLineCodeV2(insertMbom.getDevcode().substring(0, 1)));
                dspfMbomDetailMapper.insertDspfMbomDetail(dspfMbomDetailDO);
            });


            //如果是成品码，继续获取子集物料码的扩展属性进行插入
            if ("成品码".equals(i.getTypeName())) {
                DspfMbomBomDO dspdo = new DspfMbomBomDO();
                dspdo.setMbomcode(i.getObjectNumber());

                // 获取BOM结构树
                PartBomTreeByFilterVO bomTreeVOCpm = commonService.queryChildParts(
                        i.getObjectNumber(),
                        i.getOid().toString(),
                        "Design",
                        Boolean.FALSE,
                        null,
                        "N",
                        Boolean.TRUE
                );
                //子结构
                List<PartBomTree> partree = bomTreeVOCpm.getPartBomTreeList().stream()
                        .filter(partBomTree -> partBomTree != null && !"0".equals(partBomTree.getLevel()))
                        .collect(Collectors.toList());
                if (IterUtil.isNotEmpty(partree)) {
                    partree.stream().forEach(j -> {
                        List<TyIbaDataDTO> list = dspfMbomBomMapper.getIbaMapByNumber(j.getObjectNumber());
                        Map<String, String> map = this.listChangeMap(list);
                        if (StrUtil.isEmpty(map.get("devCode"))) {
                            stringBuffer.append("【" + j.getObjectNumber() + "】的开发令扩展属性为空,");
                        }
                        Map<String, List<AttributeVO>> liMap = this.getIbaMapData(partDO.getOid(), i.getMasteredoid(),
                                                                                  TableTypeConstrant.TY_PARTUSAGELINK_OTYPE);
                        Map<BigInteger, Double> countm = this.getLinkCountMap(partDO.getOid(), i.getMasteredoid());
                        liMap.forEach((k, v) -> {
                            DspfMbomDetailDO dspdetaildo = this.setDspfMbomDetailDO(map, j, v);
                            dspdetaildo.setMaterialcount(String.valueOf(countm.get(k)));
                            dspdetaildo.setOtype(this.getOtypeByLineCode(map.get("devCode").substring(0, 1)));
                            dspdetaildo.setBomid(bomid);
                            dspdetaildo.setKid(String.valueOf(snowflakeIdComponent.getInstance().nextId()));
                            dspfMbomDetailMapper.insertDspfMbomDetail(dspdetaildo);
                        });
                    });
                }
            }
        });

    }

    /**
     * list转map
     *
     * @param ibaList
     * @return
     */
    private Map<String, String> listChangeMap(List<TyIbaDataDTO> ibaList) {
        Map<String, String> attributeMap = ibaList.stream()
                .filter(dto -> dto.getAttributeenname() != null && dto.getAttributevalue() != null)
                .collect(Collectors.toMap(
                        TyIbaDataDTO::getAttributeenname,
                        TyIbaDataDTO::getAttributevalue,
                        (existing, replacement) -> replacement
                ));
        return attributeMap;
    }

    /**
     * 根据EBOM搭建成品BOM结构逻辑
     *
     * @param rtCfgStatusInfoDO
     * @throws JsonProcessingException
     */
    private StringBuffer saveByEBOMV2(RtCfgStatusInfoDO rtCfgStatusInfoDO, StringBuffer exceptionStr) {

        /*
         * 参考EBOM结构逻辑
         *   1.根据参考EBOM码查询底层扩展属性插入bom表头表
         *   2.根据参考EBOM码查询底层bom结构插入bom表体表
         * */
        //查询EBOM详情进行表头插入
        PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(rtCfgStatusInfoDO.getEbomcode());
        String lifecycleState = partDO.getLifecyclestagekey();

        if (!"RELEASED".equals(lifecycleState)) {
            exceptionStr.append("编码【" + rtCfgStatusInfoDO.getEbomcode() + "】是非生效状态,");
        }
        PartDetailsVO partDetailsVO = typlmPartService.queryPartDetails(partDO.getOid(), partDO.getOtype());
        Map<String, List<String>> ibaAttributeMap = partDetailsVO.getIbaAttributeMap();
        if (MapUtil.isEmpty(ibaAttributeMap)) {
            exceptionStr.append("编码【" + rtCfgStatusInfoDO.getEbomcode() + "】无扩展属性,");
        }
        //表头插入
        DspfMbomBomDO insertMbom = new DspfMbomBomDO(partDetailsVO, ibaAttributeMap, rtCfgStatusInfoDO);
        if (StrUtil.isEmpty(insertMbom.getDevcode())) {
            exceptionStr.append("编码【" + rtCfgStatusInfoDO.getEbomcode() + "】开发令属性为空,");
            return exceptionStr;
        }
        String rzvalue = rtCfgStatusInfoMapper.selectRzByInfoid(rtCfgStatusInfoDO.getStatusid());
        insertMbom.setCertification(rzvalue);
        insertMbom.setFCreateusername(TyAccountContext.getUser().getName());
        String bomid = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        String otype = this.getOtypeByLineCodeV2(insertMbom.getDevcode().substring(0, 1));
        insertMbom.setOtype(otype);
        insertMbom.setBomid(bomid);
        dspfMbomBomMapper.insertDspfMbomBom(insertMbom);

        // 获取BOM结构树
        PartBomTreeByFilterVO bomTreeVO = commonService.queryChildParts(
                rtCfgStatusInfoDO.getEbomcode(),
                partDO.getOid().toString(),
                "Design",
                Boolean.FALSE,
                null,
                "1",
                Boolean.TRUE
        );
        //筛选子项，且根据编码去重
        Set<String> seen = new HashSet<>();
        List<PartBomTree> partBomTrees = bomTreeVO.getPartBomTreeList().stream()
                .filter(partBomTree -> partBomTree != null && !"0".equals(partBomTree.getLevel()))
                .filter(partBomTree -> seen.add(partBomTree.getObjectNumber()))
                .collect(Collectors.toList());
        if (IterUtil.isNotEmpty(partBomTrees)) {
            partBomTrees.stream().forEach(i -> {
                //判断子项数据中是否还有子项数据，如果有需要进行递归继续往下拉取数据
                if ("EBOM号".equals(i.getTypeName())) {
                    rtCfgStatusInfoDO.setEbomcode(i.getObjectNumber());
                    saveByEBOMV2(rtCfgStatusInfoDO, exceptionStr);
                } else {
                    //判断EBOM下面是否是图样号和标准件不是需要抛异常让用户先处理
                    if (!"图样代号".equals(i.getTypeName()) && !"标准件".equals(i.getTypeName())) {
                        exceptionStr.append("【" + i.getObjectNumber() + "】不是图样代号和标准件,");
                    }
                    //判断物料码是不是已生效状态
                    if (!"已生效".equals(i.getLifecycleState())) {
                        exceptionStr.append("【" + i.getObjectNumber() + "】不是生效状态,");
                    }
                    //判断成品码下面的物料是否是检入状态，如果不是检入也要抛异常让用户处理先
                    if (!"c/i".equals(i.getCheckInOrCheckOut())) {
                        exceptionStr.append("【" + i.getObjectNumber() + "】不是检入状态,");
                    }

                    //根据图样号（标准件）获取扩展属性进行插入（通过sql查询）
                    List<TyIbaDataDTO> ibaList = dspfMbomBomMapper.getIbaMapByNumber(i.getObjectNumber());
                    if (IterUtil.isEmpty(ibaList)) {
                        exceptionStr.append("【" + i.getObjectNumber() + "】扩展属性为空,");
                    }
                    Map<String, String> attributeMap = this.listChangeMap(ibaList);
                    Map<String, List<AttributeVO>> linkMap = this.getIbaMapData(partDO.getOid(), i.getMasteredoid(),
                                                                                TableTypeConstrant.TY_PARTUSAGELINK_OTYPE);
                    Map<BigInteger, Double> countMap = this.getLinkCountMap(partDO.getOid(), i.getMasteredoid());
                    linkMap.forEach((key, valueList) -> {
                        DspfMbomDetailDO dspfMbomDetailDO = this.setDspfMbomDetailDO(attributeMap, i, valueList);
                        Double aDouble = countMap.get(new BigInteger(key));
                        dspfMbomDetailDO.setMaterialcount(
                                String.valueOf(aDouble) == null ? "0" : String.valueOf(aDouble));
                        if (StrUtil.isNotEmpty(insertMbom.getDevcode())) {
                            dspfMbomDetailDO.setOtype(otype);
                        }
                        dspfMbomDetailDO.setKid(String.valueOf(snowflakeIdComponent.getInstance().nextId()));
                        dspfMbomDetailDO.setBomid(bomid);
                        dspfMbomDetailMapper.insertDspfMbomDetail(dspfMbomDetailDO);
                    });
                }
            });
        }


        return exceptionStr;
    }

    /**
     * 获取Link关系属性,或者获取扩展属性(需要改usageLinkOids，otype)
     *
     * @param oid
     * @param masteredoid
     */
    private Map<String, List<AttributeVO>> getIbaMapData(BigInteger oid, String masteredoid, String otype) {

        List<PartUsageLinkDO> beforeUsageLinkList = typlmPartUsageLinkService.queryPartUsageLinkByAoidBoid(
                oid, new BigInteger(masteredoid));  //第一个参数aid 父的OID 第二个参数boid 子的MasterOID
        //        List<BigInteger> usageLinkOids = beforeUsageLinkList.stream()
        //                .map(PartUsageLinkDO::getOid)
        //                .filter(Objects::nonNull)
        //                .collect(Collectors.toList());
        //        Map<String, List<AttributeVO>> ibaValuePart = typlmAttributeValueService.getAttrValueTableByEntitys(
        //                usageLinkOids
        //                , TableTypeConstrant.TY_PARTUSAGELINK_OTYPE);
        Map<BigInteger, Double> map1 = beforeUsageLinkList.stream()
                .filter(Objects::nonNull)
                .filter(link -> link.getOid() != null)
                .filter(link -> link.getAmount() != null)
                .collect(Collectors.toMap(
                        PartUsageLinkDO::getOid,
                        PartUsageLinkDO::getAmount,
                        (existing, replacement) -> existing
                ));
        List<BigInteger> usageLinkOids = new ArrayList<>(map1.keySet());
        Map<String, List<AttributeVO>> ibaValuePart = typlmAttributeValueService.getAttrValueTableByEntitys(
                usageLinkOids
                , otype);
        return ibaValuePart;
    }

    private Map<BigInteger, Double> getLinkCountMap(BigInteger oid, String masteredoid) {

        List<PartUsageLinkDO> beforeUsageLinkList = typlmPartUsageLinkService.queryPartUsageLinkByAoidBoid(
                oid, new BigInteger(masteredoid));  //第一个参数aid 父的OID 第二个参数boid 子的MasterOID
        Map<BigInteger, Double> linkCountMap = beforeUsageLinkList.stream()
                .filter(Objects::nonNull)
                .filter(link -> link.getOid() != null)
                .filter(link -> link.getAmount() != null)
                .collect(Collectors.toMap(
                        PartUsageLinkDO::getOid,
                        PartUsageLinkDO::getAmount,
                        (existing, replacement) -> existing
                ));
        return linkCountMap;
    }

    /**
     * 给BOM表体赋值
     *
     * @param map
     * @param bomTree
     * @return
     */
    private DspfMbomDetailDO setDspfMbomDetailDO(Map<String, String> map, PartBomTree bomTree,
                                                 List<AttributeVO> linkList) {
        DspfMbomDetailDO dspfMbomDetailDO = new DspfMbomDetailDO();

        //根据link属性设置段号、装配位置、制造属性
        if (IterUtil.isNotEmpty(linkList)) {
            for (AttributeVO attributeVO : linkList) {
                //段号
                if ("SegmNum".equals(attributeVO.getAttributeEnName())) {
                    dspfMbomDetailDO.setPositionnum(attributeVO.getAttributeValue());
                }
                //装配位置
                if ("Position".equals(attributeVO.getAttributeEnName())) {
                    dspfMbomDetailDO.setAssemblyposition(attributeVO.getAttributeValue());
                }
                //制造属性
                if ("ManufacturingAttr".equals(attributeVO.getAttributeEnName())) {
                    dspfMbomDetailDO.setManufactureattr(attributeVO.getAttributeValue());
                }
                //ROHS定价
                if ("rohsPriceDiff".equals(attributeVO.getAttributeEnName())) {
                    dspfMbomDetailDO.setPricing(attributeVO.getAttributeValue());
                }
            }
        }


        if (StrUtil.isNotEmpty(bomTree.getObjectNumber())) {
            dspfMbomDetailDO.setPatterncode(bomTree.getObjectNumber().substring(0, 13));
            if (bomTree.getObjectNumber().length() > 13) {
                dspfMbomDetailDO.setMaterialcode(bomTree.getObjectNumber());
            }
        }
        dspfMbomDetailDO.setFCreatedate(new Date());
        dspfMbomDetailDO.setFCreateusername(TyAccountContext.getUser().getName());
        dspfMbomDetailDO.setVerid(bomTree.getVersion());
        dspfMbomDetailDO.setDescription(map.get("Describe") == null ? "" : map.get("Describe"));
        //        String roHS = map.get("RoHS")==null?"":map.get("RoHS");
        //根据枚举id获取枚举具体的值
        //        if(StrUtil.isNotEmpty(roHS)){
        //            //根据图号编码获取属性卡片id
        //            String refobjbaseoid = dspfMbomDetailMapper.selectRefobjbaseoidByNumber(bomTree.getObjectNumber());
        //            //根据属性卡片id拿到RoHS的值
        //            String choid = dspfMbomDetailMapper.selectRohsid(refobjbaseoid);
        //            String value = dspfMbomDetailMapper.selectRohsValue(choid,roHS);
        //            if("有".equals(value)){
        //                dspfMbomDetailDO.setPricing(1);
        //            }else {
        //                dspfMbomDetailDO.setPricing(2);
        //            }
        //
        //        }
        return dspfMbomDetailDO;
    }

    private TyplmFolderObjDTO tyQueryEBOMCode(DspfMbomBomDO dspfMbomBomDO) {
        String jsonQueryCode = "{\"subFolderOid\":\"715670069120204800\",\"subFolderOtype\":\"ty.inteplm.folder.CTySubFolder\",\"curPage\":1,\"pageSize\":20,\"needCount\":false,\"keyword\":\"YG900010\",\"subFolderFilterDTO\":{\"oid\":\"363292770112602112\",\"otype\":\"ty.inteplm.folder.CTyTableViewDescriptor\",\"name\":\"全部\",\"createstamp\":\"2022-11-21 23:21:09\",\"updatestamp\":\"2024-05-08 16:07:41\",\"modifystamp\":\"2024-05-08 16:07:41\",\"updatecount\":\"2\",\"markfordelete\":\"0\",\"identifierRef\":{\"oid\":\"363292770112602112\",\"otype\":\"ty.inteplm.folder.CTyTableViewDescriptor\"},\"containeroid\":\"251680307611926528\",\"containerotype\":\"ty.inteplm.product.CTyPDMLinkProduct\",\"attributes\":\"All\",\"tableid\":\"folderbrowser_PDM\",\"system\":\"1\",\"published\":\"1\",\"owneroid\":\"105\",\"ownerotype\":\"ty.inteplm.org.CTyUser\",\"matchall\":\"1\",\"inheriteddomain\":\"0\",\"hidden\":\"0\",\"frozencolumns\":\"-1\",\"domainoid\":\"251680307620315136\",\"domainotype\":\"ty.inteplm.domain.CTyDomain\",\"viewgroup\":\"folder\",\"systemdefault\":1,\"searchCondition\":{\"typeList\":[],\"conditionJoint\":\"and\",\"conditionGroups\":[],\"pageNum\":1,\"pageSize\":20,\"needIBA\":false,\"columns\":[{\"propertyName\":\"changestatus\",\"displayName\":\"更改状况\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"50\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"graphical\",\"displayName\":\"图形标识\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"50\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"thumbnailFile\",\"displayName\":\"缩略图\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"120\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"identifier\",\"displayName\":\"标识\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"300\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"state\",\"displayName\":\"生命周期状态\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"typeDefName\",\"displayName\":\"类型\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"modifier\",\"displayName\":\"修改者\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"modifystamp\",\"displayName\":\"修改时间\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false}],\"needThumbnailFile\":false,\"searchType\":1},\"searchColumnList\":[{\"propertyName\":\"changestatus\",\"displayName\":\"更改状况\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"50\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"graphical\",\"displayName\":\"图形标识\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"50\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"thumbnailFile\",\"displayName\":\"缩略图\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"120\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"identifier\",\"displayName\":\"标识\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"300\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"state\",\"displayName\":\"生命周期状态\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"typeDefName\",\"displayName\":\"类型\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"modifier\",\"displayName\":\"修改者\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false},{\"propertyName\":\"modifystamp\",\"displayName\":\"修改时间\",\"masterProperty\":false,\"fixed\":\"\",\"width\":\"80\",\"sortable\":false,\"fieldList\":[],\"virtual\":false,\"foreignColumnMaster\":false,\"canNotRemove\":false,\"enum\":false}],\"info\":{\"classDisplay\":\"\",\"typeDisplay\":\"所有类型\",\"contextDisplay\":\"所有上下文\",\"conditionDisplayList\":[],\"columnDisplay\":\"更改状况、图形标识、缩略图、标识、生命周期状态、类型、修改者、修改时间\"},\"createSystemView\":false,\"needReturnOptionColumn\":false,\"clazzDisplayName\":\"\",\"displayFullName\":\"全部\"}}";
        TySubFolderFilterQuery tySubFolderFilterQuery = JSONUtil.toBean(jsonQueryCode, TySubFolderFilterQuery.class);
        tySubFolderFilterQuery.setKeyword(dspfMbomBomDO.getBarecode());
        PageInfo<TyplmFolderObjDTO> folderObjectByFilter = typlmSubFilterObjectService.getFolderObjectByFilter(
                tySubFolderFilterQuery);
        List<TyplmFolderObjDTO> typlmFolderObjDTOS = folderObjectByFilter.getList();
        if (IterUtil.isEmpty(typlmFolderObjDTOS)) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                    "未查询到【" + dspfMbomBomDO.getBarecode() + "】数据");
        }
        List<TyplmFolderObjDTO> filteredList = typlmFolderObjDTOS.stream()
                .filter(objDTO -> dspfMbomBomDO.getBarecode().equals(objDTO.getObjectNumber()))
                .collect(Collectors.toList());
        if (IterUtil.isEmpty(filteredList)) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                    "未查询到【" + dspfMbomBomDO.getBarecode() + "】数据");
        }
        TyplmFolderObjDTO typlmFolderObjDTO = filteredList.get(0);
        return typlmFolderObjDTO;
    }

    /**
     * 根据线体获取图号类型（机组、动力、传动）0动力/1机组/2传动 (弃用)
     *
     * @param lineCode
     * @return
     */
    private String getOtypeByLineCode(String lineCode) {
        ProductSpectrumDTO allProductSpectrum = devOrderService.getAllProductSpectrum();
        List<ProductSpectrumDTO> list = allProductSpectrum.getList();
        for (int i = 0; i < list.size(); i++) {
            String name = list.get(i).getName();
            List<ProductSpectrumDTO> dtoList = list.get(i).getList();
            for (int j = 0; j < dtoList.size(); j++) {
                String lineName = dtoList.get(j).getName();
                //获取产线名称最后一个字符为产线code
                String code = lineName.substring(lineName.length() - 1);
                if (lineCode.equals(code)) {
                    if ("OPE".equals(name)) {//终端（机组）
                        return "1";
                    }
                    if ("机组".equals(name)) {//终端（机组）
                        return "1";
                    }
                    if ("动力".equals(name)) {
                        return "0";
                    }
                    if ("传动".equals(name)) {
                        return "2";
                    }
                }

            }
        }
        return "";
    }

    /**
     * 根据线体判断是（机组、动力、传动）0动力Z/1机组/2传动H
     *
     * @param lineCode
     * @return
     */
    private String getOtypeByLineCodeV2(String lineCode) {
        if ("H".equals(lineCode)) {
            return "2";
        } else if ("Z".equals(lineCode)) {
            return "0";
        } else {
            return "1";
        }
    }

    private String getNowMasterOidByOid(String masterOid) {
        String oid = rtCfgStatusInfoMapper.getNowMasterOidByOid(masterOid);
        return oid;
    }


    @Override
    public ResponseResult getRtCfgBOMByPartNumber(BomQueryDTO dto) {
        if (dto != null && dto.getOldpartnumber() != null) {
            // 开始分页
            PageHelper.startPage(dto.getPageNum(), dto.getPageSize());

            //因为穿过来的不一定是图号，有可能直接传输的物料码，这里需要对物料码进行处理获取前面13位的图号
            if (dto.getOldpartnumber().length() > 13) {
                dto.setOldpartnumber(dto.getOldpartnumber().substring(0, 13));
            }

            // 执行查询 获取物料
            List<LikeBomVO> rtCfgBomDOList = dspfMbomDetailMapper.getRtCfgBOMByPartNumber(dto.getOldpartnumber());
            if (IterUtil.isEmpty(rtCfgBomDOList)) {
                throw RTErrorCodeEnum.STATUS_NOT_RELEASED_ERROR.getException("无已生效的物料衍生码或不是直采、自制件");
            }

            // 包装成分页结果
            com.github.pagehelper.PageInfo<LikeBomVO> pageInfo = new com.github.pagehelper.PageInfo<>(rtCfgBomDOList);

            if (rtCfgBomDOList == null || rtCfgBomDOList.isEmpty()) {
                return ResponseResult.fail("500", "没有查到此【" + dto.getOldpartnumber() + "的物料信息】，请检查！");
            }

            return ResponseResult.success(pageInfo);
        }
        return ResponseResult.fail("500", "请传入图号编码！");

    }

    @Override
    public ResponseResult getRtCfgBOMByDrawing(BomQueryDTO dto) {

        //根据开发令查询所有EBOM号下面的图号
        if (dto != null && dto.getDevCode() != null) {
            //查询EBOM
            List<String> eBomCodes = dspfMbomDetailMapper.getRtCfgBOMByDevCode(dto.getDevCode());
            if (IterUtil.isEmpty(eBomCodes)) {
                throw RTErrorCodeEnum.STATUS_NOT_RELEASED_ERROR.getException("无已生效的EBOM号");
            }
            //根据EBOM号拉取所有的图号
            List<PartBomTree> partBomTreeListAll = new ArrayList<>();
            for (String ebom:eBomCodes){
                PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(ebom);
                // 获取BOM结构树
                PartBomTreeByFilterVO bomTreeVO = commonService.queryChildParts(
                        ebom,
                        partDO.getOid().toString(),
                        "Design",
                        Boolean.FALSE,
                        null,
                        "N",
                        Boolean.TRUE
                );
                List<PartBomTree> partBomTreeList = bomTreeVO.getPartBomTreeList();
                //筛选图号
                if(IterUtil.isNotEmpty(partBomTreeList)){
                    List<PartBomTree> partBomTrees = bomTreeVO.getPartBomTreeList().stream()
                            .filter(partBomTree -> "图样代号".equals(partBomTree.getTypeName()))
                            .collect(Collectors.toList());
                    partBomTreeListAll.addAll(partBomTrees);
                }

            }
            if (IterUtil.isEmpty(partBomTreeListAll)) {
                return ResponseResult.fail("500", "没有查到此【" + dto.getDevCode() + "】开发令的图号信息，请检查！");
            }
            List<LikeBomVO> drawingCodeData = this.convertDrawingCode(partBomTreeListAll);
            // 将图号信息转换为前端所需要的对象包装成分页结果
            com.github.pagehelper.PageInfo<LikeBomVO> pageInfo = new com.github.pagehelper.PageInfo<>(drawingCodeData);

            return ResponseResult.success(pageInfo);
        }
        return ResponseResult.fail("500", "请先传入开发令！");

    }

    /**
     * 图样代号底层对象转换
     * @param partBomTreeListAll
     * @return
     */
    private List<LikeBomVO> convertDrawingCode(List<PartBomTree> partBomTreeListAll) {
        List<LikeBomVO> list = new ArrayList<>();
        for (PartBomTree partBomTree:partBomTreeListAll){
            LikeBomVO likeBomVO = new LikeBomVO(partBomTree);
            list.add(likeBomVO);
        }
        return list;
    }


    @Override
    public ResponseResult updateEbomPartNumberByPartNumber(DspfMbomDetailDO dspfMbomDetailDO) {
        if (ObjectUtil.isNotEmpty(dspfMbomDetailDO)) {
            // 获取当前登录用户信息
            UserDO user = TyAccountContext.getUser();
            dspfMbomDetailDO.setFModifyusername(user != null ? user.getName() : "");
            dspfMbomDetailDO.setFModifydate(String.valueOf(new Date()));
            dspfMbomDetailDO.setFModifyuserid(String.valueOf(user.getOid()));
            dspfMbomDetailDO.setFCreateusername(user.getName());
            int i = dspfMbomDetailMapper.updateDspfMbomDetail(dspfMbomDetailDO);
            if (i == 0) {
                ResponseResult.fail("500", "修改失败！请刷新后再尝试！");
            }
            return ResponseResult.success();
        }

        return ResponseResult.fail("500", "参数为空,请检查参数！");
    }

    /**
     * 调用底层方法进行成品BOM搭建
     *
     * @param rtCfgBomDTO
     */
    private void buildBOM(RtCfgBomDTO rtCfgBomDTO) {
        String jsonConfig = "{\"folderName\":\"成品BOM\",\"folderId\":\"734048728173330432\",\"folderPath\":\"/开发人员专用/成品BOM\",\"containerID\":\"707053057766981632\",\"containerType\":\"ty.inteplm.product.CTyPDMLinkProduct\",\"containerName\":\"开发人员专用\",\"productPath\":\"开发人员专用\",\"typeOid\":\"734033424986718208\",\"typeName\":\"成品BOM\",\"classId\":\"\",\"classDisplayName\":\"\",\"productID\":\"707053057766981632\",\"typeOType\":\"ty.inteplm.part.CTyPart|FinishedProductBOM\",\"lifecycleTemplate\":\"润通通用生命周期模板\",\"partNumber\":\"part202509061358042964939\",\"lifecycleTemplateID\":\"732949514087694336\",\"lifecycleTemplateName\":\"润通通用生命周期模板\",\"partView\":\"Design\",\"Stage\":\"阶段1\",\"BusinessEdition\":\"V1\",\"ChangeContent\":\"更改内容1\",\"number\":\"part202509061358042964939\",\"name\":\"名称1\",\"genericType\":\"standard\",\"category\":\"standard\",\"collapsible\":\"0\",\"enditem\":\"0\",\"description\":\"描述1\",\"assemblyMode\":\"component\",\"source\":\"Make\",\"unit\":\"PCS\",\"phantom\":\"0\",\"security\":\"非密\",\"securitylabels\":\"非密\",\"checkoutState\":\"\",\"lockdate\":\"\",\"lockeroName\":\"\",\"lifecycleMasterName\":\"润通通用生命周期模板\",\"lifecycleState\":\"Creating\",\"creatorName\":\"\",\"modifierName\":\"\",\"ownername\":\"\",\"creationTime\":\"\",\"updatecount\":\"\",\"lastupdatestampstr\":\"\",\"ibaAttribute\":{\"Stage\":[\"阶段1\"],\"BusinessEdition\":[\"V1\"],\"ChangeContent\":[\"更改内容1\"]}}";
        String jsonBomAddBatchCheck = "{\"bomAddBatchCheckParentDTOList\":[{\"parentNumber\":\"part202509061358042964939\",\"parentMasterId\":\"734101118771773440\",\"parentViewName\":\"Design\",\"childList\":[{\"number\":\"18100-Z360110-0001\",\"masterId\":\"728682524089974784\",\"viewName\":\"Design\"}]}],\"isCheckView\":true,\"isCheckCircularReference\":true}";
        String jsonSaveBomViewListImmediately = "[{\"parent\":{\"oid\":\"734112810650025984\",\"otype\":\"ty.inteplm.part.CTyPart\",\"name\":\"名称1\",\"viewID\":\"323899843229581312\"},\"bomTreeNodeList\":[{\"oid\":\"\",\"partoid\":\"733666789905383424\",\"partotype\":\"ty.inteplm.part.CTyPart\",\"objOid\":\"733666789905383424\",\"objOtype\":\"ty.inteplm.part.CTyPart\",\"oriAreference\":\"\",\"oriAmount\":\"1\",\"amount\":\"1\",\"masterpartnumber\":\"18100-Z310110-0001\",\"mastername\":\"衍生物料码1\",\"parentPartNumber\":\"part202509061358042964939\",\"parentPartName\":\"名称1\",\"version\":\"A\",\"lifecyclestagekey\":\"Creating\",\"iterationid\":\"2\",\"value\":20,\"action\":\"add\",\"viewName\":\"Design\"}],\"addBOMFlag\":true}]";
        InsertPartDTO insertPartDTO = JSONUtil.toBean(jsonConfig, InsertPartDTO.class);
        LinkedHashMap<String, List<String>> ibaAttribute = new LinkedHashMap<>();
        //预留扩展属性字段添加
        //        ibaAttribute.put("productType", Arrays.asList());
        //        ibaAttribute.put("devCode", Arrays.asList());


        insertPartDTO.setIbaAttribute(ibaAttribute);
        insertPartDTO.setName(rtCfgBomDTO.getFarthername());
        insertPartDTO.setPartNumber("part" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmssSSS"));
        ArgumentUtils.checkArgumentNull(insertPartDTO.getPartView(),
                                        PartBomErrorCodeEnum.EXCEPTION_PARAM_VIEW_ID_IS_EMPTY.getLocaleMessage());
        PdmPartInfoVO partInfoVO = typlmPdmPartService.insertPart(new UploadFileDTO(), new LinkedHashMap<>(),
                                                                  insertPartDTO);
        //将搭建成功的成品BOM OID存入需求状态表
        rtCfgBomMapper.updateStatusInfoByBomOid(rtCfgBomDTO.getInfoid(), partInfoVO.getOid());

        //继续调用底层接口搭建BOM子集物料数据【第一个接口】
        // 解析JSON字符串为JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(jsonBomAddBatchCheck);

        // 获取bomAddBatchCheckParentDTOList数组
        JSONArray parentList = jsonObject.getJSONArray("bomAddBatchCheckParentDTOList");
        //根据成品BOMOID查询出parentNumber、parentMasterId、parentViewName字段
        Map<String, Object> map = rtCfgBomMapper.selectParentByBomOidOut(partInfoVO.getPartNumber());
        if (MapUtil.isNotEmpty(map)) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                    "当前成品码【" + partInfoVO.getPartNumber() + "】已被检出");
        }
        map = rtCfgBomMapper.selectParentByBomOidIn(partInfoVO.getPartNumber());
        // 遍历父对象列表
        for (Object parentObj : parentList) {
            JSONObject parent = JSONUtil.parseObj(parentObj);

            // 修改父对象的相关字段
            parent.set("parentNumber", map.get("parentNumber").toString());
            parent.set("parentMasterId", map.get("parentMasterId").toString());
            parent.set("parentViewName", "Design");

            // 获取子对象列表
            JSONArray childList = parent.getJSONArray("childList");

            // 遍历子对象列表
            for (Object childObj : childList) {
                JSONObject child = JSONUtil.parseObj(childObj);
                // 修改子对象的相关字段
                child.set("number", rtCfgBomDTO.getPartnumber());
                String masterId = rtCfgBomMapper.selectMasterIdByNumber(rtCfgBomDTO.getPartnumber());
                child.set("masterId", masterId);
                child.set("viewName", "Design");
            }
        }
        BomAddBatchCheckDTO bomAddBatchCheckDTO = JSONUtil.toBean(jsonObject.toStringPretty(),
                                                                  BomAddBatchCheckDTO.class);
        ResponseResult<Boolean> booleanResponseResult = typlmBomController.bomAddBatchCheck(bomAddBatchCheckDTO);
        if (!booleanResponseResult.getData()) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                    "成品BOM搭建子集物料数据异常【/rest/v1/bom/bomAddBatchCheck接口】");
        }

        //继续调用底层接口搭建BOM子集物料数据【第二个接口】
        JSONArray jsonArray = JSONUtil.parseArray(jsonSaveBomViewListImmediately);

        // 遍历数组中的每个对象
        for (Object obj : jsonArray) {
            JSONObject jsonObjectVi = JSONUtil.parseObj(obj);

            // 获取parent对象
            //            JSONObject parent = jsonObjectVi.getJSONObject("parent");

            // 替换parent对象中的所有值
            //            parent.set("oid", partInfoVO.getOid());
            //            parent.set("otype", map.get("otype"));
            //            parent.set("name", map.get("name"));
            //            parent.set("viewID", map.get("viewID"));

            // 如果需要完全替换parent对象，可以使用以下方式
            JSONObject newParent = JSONUtil.createObj()
                    .set("oid", partInfoVO.getOid().toString())
                    .set("otype", map.get("otype"))
                    .set("name", map.get("name"))
                    .set("viewID", map.get("viewID").toString());
            jsonObjectVi.set("parent", newParent);

            // 获取bomTreeNodeList数组
            JSONArray bomList = jsonObjectVi.getJSONArray("bomTreeNodeList");

            // 遍历bomTreeNodeList中的每个对象
            for (Object bomObj : bomList) {
                JSONObject bomNode = JSONUtil.parseObj(bomObj);

                // 替换指定字段值
                Map<String, Object> mapBOMNode = rtCfgBomMapper.selectParentByBomOidOut(partInfoVO.getPartNumber());
                if (MapUtil.isNotEmpty(mapBOMNode)) {
                    throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                            "当前成品码【" + partInfoVO.getPartNumber() + "】已被检出");
                }
                mapBOMNode = rtCfgBomMapper.selectParentByBomOidIn(partInfoVO.getPartNumber());
                bomNode.set("mastername", rtCfgBomDTO.getNamee());
                bomNode.set("masterpartnumber", rtCfgBomDTO.getPartnumber());
                bomNode.set("objOid", rtCfgBomDTO.getOid().toString());
                bomNode.set("objOtype", mapBOMNode.get("otype"));
                bomNode.set("parentPartName", map.get("name"));
                bomNode.set("parentPartNumber", map.get("parentNumber"));
                bomNode.set("partoid", rtCfgBomDTO.getOid().toString());
                bomNode.set("partotype", map.get("otype"));
            }
        }
        List<PartBomView> partBomViews = JSONUtil.toList(jsonArray, PartBomView.class);
        ResponseResult<Map<BigInteger, Long>> mapResponseResult = typlmBomController.saveBomViewListImmediately(
                partBomViews);
        if (MapUtil.isEmpty(mapResponseResult.getData())) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                    "成品BOM搭建子集物料数据异常【/rest/v1/bom/saveBomViewListImmediately接口】");
        }


    }

    @Override
    public ResponseResult getRtCfgBuildBOMList(BomQueryDTO queryBomDTO) {

        //根据当前节点名称确定是 0动力、1机组（终端）、2传动
        Integer nodeType = null;
        String currentTaskName = queryBomDTO.getCurrentTaskName();
        if (currentTaskName.contains("终端")) {
            nodeType = 1;
        } else if (currentTaskName.contains("动力")) {
            nodeType = 0;
        } else if (currentTaskName.contains("传动")) {
            nodeType = 2;
        }

        RtCfgStatusDTO rtCfgStatusDTO = new RtCfgStatusDTO();
        rtCfgStatusDTO.setOid(queryBomDTO.getOid());
        RtCfgStatusInfoDO rtCfgStatusInfoDO = rtCfgStatusInfoMapper.selectByStatusCode(rtCfgStatusDTO);
        if (ObjectUtil.isEmpty(rtCfgStatusInfoDO)) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("没有此需求状态表数据");
        }
        //        PageHelper.startPage(queryBomDTO.getPageNum(), queryBomDTO.getPageSize());
        //        List<RtCfgBomDO> list = rtCfgBomMapper.getRtCfgBuildBOMList(rtCfgStatusInfoDO.getStatusid(),queryBomDTO.getViewName());
        //        PageInfo<RtCfgBomDO> pageInfo =new PageInfo<>(list);

        //根据需求状态表id查询BOM结构

        List<DspfMbomBomDTO> dtos = new ArrayList<>();
        List<DspfMbomBomDO> dspfMbomBomDOS = dspfMbomBomMapper.selectDspfMbomBomByStatusId(
                rtCfgStatusInfoDO.getStatusid(), null);
        if (IterUtil.isNotEmpty(dspfMbomBomDOS)) {
            for (DspfMbomBomDO dspfMbomBomDO : dspfMbomBomDOS) {
                List<DspfMbomDetailDO> list = dspfMbomDetailMapper.selectDspfMbomDetailListByBomid(
                        dspfMbomBomDO.getBomid(), nodeType);
                if (Integer.valueOf(dspfMbomBomDO.getOtype()) == nodeType) {
                    DspfMbomBomDTO dto = new DspfMbomBomDTO();
                    dto.setDspfMbomBomDO(dspfMbomBomDO);
                    //根据用户id，段号查询是否有搭建物料、图号的权限
                    this.getDrawingMaterialAuth(list);
                    dto.setMbomDetailDOList(list);
                    dtos.add(dto);
                }
                //查询所有
                if (nodeType == null) {
                    DspfMbomBomDTO dto = new DspfMbomBomDTO();
                    dto.setDspfMbomBomDO(dspfMbomBomDO);
                    this.getDrawingMaterialAuth(list);
                    dto.setMbomDetailDOList(list);
                    dtos.add(dto);
                }
            }
        }
        if(IterUtil.isEmpty(dtos)){
            DspfMbomBomDO dspfDO = new DspfMbomBomDO();
            dspfDO.setStatusid(rtCfgStatusInfoDO.getStatusid());
            dspfDO.setBomid(String.valueOf(snowflakeIdComponent.getInstance().nextId()));
            DspfMbomBomDTO dto = new DspfMbomBomDTO();
            dto.setDspfMbomBomDO(dspfDO);
            dto.setType(String.valueOf(nodeType));
            dtos.add(dto);
        }
        return ResponseResult.success(dtos);
    }

    private void getDrawingMaterialAuth(List<DspfMbomDetailDO> list) {
        if (IterUtil.isNotEmpty(list)) {
            list.stream().forEach(i -> {
                String drawingMaterialAuth = rtSegmNumService.getDrawingMaterialAuth(i.getPositionnum());
                i.setDrawingMaterialAuth(drawingMaterialAuth);
                //根据图号查询是否只有一个物料衍生码，是就直接赋值
                List<LikeBomVO> rtCfgBomDOList = dspfMbomDetailMapper.getRtCfgBOMByPartNumber(i.getPatterncode());
                if (IterUtil.isNotEmpty(rtCfgBomDOList) && rtCfgBomDOList.size() == 1) {
                    i.setMaterialcode(rtCfgBomDOList.get(0).getPartNumber());
                }
            });
        }
    }

    @Override
    public ResponseResult getRtCfgBuildBOMZD(BomQueryDTO queryBomDTO) {
        RtCfgStatusDTO rtCfgStatusDTO = new RtCfgStatusDTO();
        rtCfgStatusDTO.setOid(queryBomDTO.getOid());
        RtCfgStatusInfoDO rtCfgStatusInfoDO = rtCfgStatusInfoMapper.selectByStatusCode(rtCfgStatusDTO);
        List<DspfMbomBomDTO> dtos = new ArrayList<>();
        List<DspfMbomBomDO> dspfMbomBomDOS = dspfMbomBomMapper.selectDspfMbomBomByStatusId(
                rtCfgStatusInfoDO.getStatusid(), null);
        if (IterUtil.isNotEmpty(dspfMbomBomDOS)) {
            for (DspfMbomBomDO dspfMbomBomDO : dspfMbomBomDOS) {
                //查询所有
                DspfMbomBomDTO dto = new DspfMbomBomDTO();
                dto.setDspfMbomBomDO(dspfMbomBomDO);
                List<DspfMbomDetailDO> list = dspfMbomDetailMapper.selectDspfMbomDetailListByBomid(
                        dspfMbomBomDO.getBomid(), null);
                List<DspfMbomDetailDO> listZD = new ArrayList<>();
                list.stream().forEach(i -> {
                    if ("0".equals(i.getOtype())) {
                        i.setProductCode(rtCfgStatusInfoDO.getDmchengbom());
                    }
                    if ("1".equals(i.getOtype())) {
                        i.setProductCode(rtCfgStatusInfoDO.getZmchengbom());
                    }
                    if ("2".equals(i.getOtype())) {
                        i.setProductCode(rtCfgStatusInfoDO.getCdchengbom());
                    }
                    Map<String, Object> params = new HashMap<>();
                    params.put("materialCode", i.getMaterialcode());
                    params.put("status", 1);
                    Map<String, Object> map = rtZdService.queryZdInfo(params);
                    List zdList = (List) map.get("list");
                    if (IterUtil.isEmpty(zdList)) {
                        listZD.add(i);
                    }
                });
                dto.setMbomDetailDOList(listZD);
                dtos.add(dto);
            }
        }
        return ResponseResult.success(dtos);
    }

    @Override
    public void buildBOM(List<DspfMbomDetailDO> list, String productCode, RtCfgStatusInfoDO rtCfgStatusInfoDO) {
        /*
         * 成品BOM搭建逻辑
         *   1.根据需求状态表id查询自定义成品BOM表数据
         *   2.循环调用底层搭建BOM接口方法
         */
        // 获取当前登录用户信息
        UserDO user = TyAccountContext.getUser();
        if (IterUtil.isNotEmpty(list)) {
            // 使用编程式事务控制父级搭建
            //            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            //            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            //            TransactionStatus status = transactionManager.getTransaction(def);

            PdmPartInfoVO partInfoVO;
            //            try {
            //父级搭建
            partInfoVO = this.buildBOMParent(list.get(0), productCode, rtCfgStatusInfoDO);
            //根据成品BOMOID查询出parentNumber、parentMasterId、parentViewName字段
            PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(partInfoVO.getPartNumber());
            if (!"RELEASED".equals(partDO.getLifecyclestagekey())) {
                throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                        "当前成品码【" + partInfoVO.getPartNumber() + "】不是已生效状态");
            }
            Map<String, Object> map = rtCfgBomMapper.selectParentByBomOidIn(partInfoVO.getPartNumber());
            list.stream().forEach(i -> {
                //子集搭建
                this.bomAddBatchCheck(i, partInfoVO, map);
                this.saveBomViewListImmediately(i, partInfoVO, map);
            });
            // 手动提交事务，确保数据写入数据库
            //                transactionManager.commit(status);
            //            } catch (Exception e) {
            //                transactionManager.rollback(status);
            //                throw e;
            //            }


            //成品BOM视图转换 todo 经过领导开会讨论之后将转视图这一块交给SAP来做了所以下面的代码取消
            //
            //            String viewRefName = rtCfgStatusInfoMapper.selectScgcBystatusid(statusid);
            //            if (viewRefName == null) {
            //                return;
            //            }
            //
            //            // 分割并清洗 viewRefName，防止空指针和无效值
            //            String[] resultArray = Arrays.stream(viewRefName.split("[,;]"))
            //                    .map(String::trim)
            //                    .filter(s -> !s.isEmpty())
            //                    .distinct()
            //                    .toArray(String[]::new);
            //
            //            // 缓存父级信息，避免重复查询
            //            RtCfgBomPartDetailVO oldFatherPart = null;
            //
            //            for (String viewName : resultArray) {
            //                try {
            //                    //通过视图名称找到视图oid
            //                    BigInteger viewDefOid = rtCfgStatusInfoMapper.selectViewoidByViewRefName(viewName);
            //                    //转试图
            //                    ResponseResult responseResult = generateBOMToFactoryView(String.valueOf(partInfoVO.getOid()), viewName, String.valueOf(viewDefOid));
            //
            //                    if (ResponseResult.RESULT_SUCCESS.equals(responseResult.getResult())) {
            //                        Object data = responseResult.getData();
            //                        if (data == null) {
            //                            log.error("responseResult.getData() 返回 null，viewName={}, partOid={}", viewName, partInfoVO.getOid());
            //                            return;
            //                        }
            //                        PartDetailsVO newFatherPart = (PartDetailsVO) data;
            //
            //                        // 仅第一次查询父级信息
            //                        if (oldFatherPart == null) {
            ////                            oldFatherPart = typlmPartService.queryPartDetails(partInfoVO.getOid(), STATUS_OTYPE);
            //                            oldFatherPart = rtCfgBomMapper.getPartDetails(
            //                                    String.valueOf(partInfoVO.getOid()));
            //                            if (oldFatherPart == null) {
            //                                log.error("queryPartDetails 查询结果为 null，partOid={}, statusOtype={}", partInfoVO.getOid(), STATUS_OTYPE);
            //                                return;
            //                            }
            //                        }
            //
            //
            //                        //根据需求状态表id查询搭建BOM的底表信息
            //                        List<RtCfgBomDO> rtCfgBomDOS = rtCfgBomMapper.selectListByInfoId(statusid);
            //                        if (rtCfgBomDOS == null) {
            //                            rtCfgBomDOS = new ArrayList<>();
            //                        }
            //
            //                        List<RtCfgBomDO> result = new ArrayList<>(rtCfgBomDOS.size());
            //
            //                        // 提前查询 bomConfigurationVO，避免在循环中重复查询
            //                        BomConfigurationVO bomConfigurationVO = rtCfgBomMapper.selectProductTypeAndCustomerBystatusid(statusid);
            //                        if (bomConfigurationVO == null) {
            //                            bomConfigurationVO = new BomConfigurationVO();
            //                        } else {
            //                            //获取客户编码
            //                            String customecode = bomConfigurationVO.getCustomer();
            //                            String code = null;
            //                            if (customecode != null) {
            //                                int start = customecode.indexOf('[');
            //                                int end = customecode.indexOf(']');
            //                                if (start != -1 && end != -1 && end > start) {
            //                                    code = customecode.substring(start + 1, end);
            //                                }
            //                            }
            //                            bomConfigurationVO.setCustomer(code);
            //                        }
            //
            //                        String newFatherMasterOid = newFatherPart.getMasteredoid();
            //                        if (newFatherMasterOid == null) {
            //                            log.error("newFatherPart.getMasteredoid() 返回 null，partOid={}", partInfoVO.getOid());
            //                            return;
            //                        }
            //
            //                        for (RtCfgBomDO rtCfgBomDO1 : rtCfgBomDOS) {
            //                            rtCfgBomDO1.setOid(snowflakeIdComponent.getInstance().nextId());
            //                            rtCfgBomDO1.setCreatetime(new Date());
            //                            rtCfgBomDO1.setCreateuser(user.getName());
            //                            rtCfgBomDO1.setViewname(viewName);
            //
            //                            // 父级信息设置
            //                            rtCfgBomDO1.setFarthermasteroid(newFatherMasterOid);
            //                            rtCfgBomDO1.setFarthercode(newFatherPart.getNumber());
            //                            rtCfgBomDO1.setFarthername(newFatherPart.getName());
            //                            rtCfgBomDO1.setFartherotype(newFatherPart.getTypeInthid());
            //
            //                            // 自动配置 0机组/1动力
            //                            // 获取机组机型
            //                            bomConfigurationVO.setSectionNumber(rtCfgBomDO1.getSegmentnumber());
            //                            BigInteger bigInteger = rtCfgBomMapper.getLatestRtCfgBom(bomConfigurationVO);
            //                            if (bigInteger != null) {
            //                                rtCfgBomDO1.setOtype(bigInteger);
            //                            }
            //                            result.add(rtCfgBomDO1);
            //                        }
            //
            //                        if (!result.isEmpty()) {
            //                            rtCfgBomMapper.batchInsert(result);
            //                        }
            //                    } else {
            //                        log.error("生成BOM失败，viewName={}, partOid={}", viewName, partInfoVO.getOid());
            //                    }
            //
            //                } catch (Exception e) {
            //                    log.error("处理视图 {} 时发生异常，partOid={}", viewName, partInfoVO.getOid(), e);
            //                }
            //            }


        }

    }

    @Override
    public void buildBOMV2(List<DspfMbomDetailDO> list, String productCode, RtCfgStatusInfoDO rtCfgStatusInfoDO) {
        /*
         * 成品BOM搭建逻辑
         *   1.父级成品码搭建
         *   2.子级物料码搭建
         *   3.创建关系属性（段号、装配位置、制造属性）
         */

        //父级搭建
        PdmPartInfoVO pdmPartInfoVO = this.buildBOMParent(list.get(0), productCode, rtCfgStatusInfoDO);
        PartBomView partBomView = new PartBomView();
        PartBomTreeNode parent = new PartBomTreeNode();
        parent.setOid(pdmPartInfoVO.getOid());
        parent.setOtype(pdmPartInfoVO.getOtype());
        parent.setViewID(pdmPartInfoVO.getViewdefoid());
        partBomView.setParent(parent);

        //删除关系属性
        typlmPartUsageLinkService.batchDeletePartUsageLink(
                rtPartMapper.batchQueryPartUsageLinkDOByPartOid(Collections.singletonList(parent.getOid())));

        //子级搭建
        List<PartBomTreeNode> bomTreeNodeList = new ArrayList<>();
        //关系属性集合
        List<SaveObjIBADTO> objWithIbaList = new ArrayList<>();
        if (IterUtil.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                PartBomTreeNode partBomTreeNode = new PartBomTreeNode();
                PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(list.get(i).getMaterialcode());
                partBomTreeNode.setViewName(RTPlmConstant.VIEW_DESIGN);
                partBomTreeNode.setPartoid(String.valueOf(partDO.getOid()));
                partBomTreeNode.setPartotype(partDO.getOtype());
                partBomTreeNode.setAmount(Double.valueOf(list.get(i).getMaterialcount()));//数量
                partBomTreeNode.setMasterpartnumber(list.get(i).getMaterialcode());
                partBomTreeNode.setParentPartNumber(productCode);
                partBomTreeNode.setValue(Long.valueOf((i + 1) * 10));//行号
                partBomTreeNode.setAction("add");
                bomTreeNodeList.add(partBomTreeNode);
            }

        }
        partBomView.setBomTreeNodeList(bomTreeNodeList);
        Map<BigInteger, Long> map = typlmPartBomAdapter.saveBomViewImmediately(partBomView);
        // 将 map 的 key 赋值到 usageLinkOid
        Map<Long, BigInteger> reversedMap = map.entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
        for (int i = 0; i < list.size(); i++) {
            //创建新的关系属性
            List<IbaDTO> objIbaList = new ArrayList<>();
            IbaDTO ibaDTO1 = new IbaDTO();
            ibaDTO1.setKey("SegmNum");
            ibaDTO1.setValue(list.get(i).getPositionmaterial());
            objIbaList.add(ibaDTO1);
            IbaDTO ibaDTO2 = new IbaDTO();
            ibaDTO2.setKey("ManufacturingAttr");
            ibaDTO2.setValue(list.get(i).getManufactureattr());
            objIbaList.add(ibaDTO2);
            IbaDTO ibaDTO3 = new IbaDTO();
            ibaDTO3.setKey("Position");
            ibaDTO3.setValue(list.get(i).getAssemblyposition());
            objIbaList.add(ibaDTO3);

            SaveObjIBADTO saveObjIBADTO = new SaveObjIBADTO();
            CTyEntityBaseDO ctyEntityBaseDO = new CTyEntityBaseDO();
            ctyEntityBaseDO.setOid(reversedMap.get((i + 1) * 10));
            ctyEntityBaseDO.setOtype(TableTypeConstrant.TY_PARTUSAGELINK_OTYPE);
            saveObjIBADTO.setCTyEntityBaseDO(ctyEntityBaseDO);
            saveObjIBADTO.setObjIbaList(objIbaList);
            objWithIbaList.add(saveObjIBADTO);
        }
        typlmAttributeValueService.batchSaveIBAByObjList(objWithIbaList, false);

    }


    private void saveBomViewListImmediately(DspfMbomDetailDO rtCfgBomDO, PdmPartInfoVO partInfoVO,
                                            Map<String, Object> map) {
        String jsonSaveBomViewListImmediately = "[{\"parent\":{\"oid\":\"734112810650025984\",\"otype\":\"ty.inteplm.part.CTyPart\",\"name\":\"名称1\",\"viewID\":\"323899843229581312\"},\"bomTreeNodeList\":[{\"oid\":\"\",\"partoid\":\"733666789905383424\",\"partotype\":\"ty.inteplm.part.CTyPart\",\"objOid\":\"733666789905383424\",\"objOtype\":\"ty.inteplm.part.CTyPart\",\"oriAreference\":\"\",\"oriAmount\":\"1\",\"amount\":\"1\",\"masterpartnumber\":\"18100-Z310110-0001\",\"mastername\":\"衍生物料码1\",\"parentPartNumber\":\"part202509061358042964939\",\"parentPartName\":\"名称1\",\"version\":\"A\",\"lifecyclestagekey\":\"Creating\",\"iterationid\":\"2\",\"value\":20,\"action\":\"add\",\"viewName\":\"Design\"}],\"addBOMFlag\":true}]";
        JSONArray jsonArray = JSONUtil.parseArray(jsonSaveBomViewListImmediately);

        // 遍历数组中的每个对象
        for (int i = 0; i < jsonArray.size(); i++) {
            Object obj = jsonArray.get(i);
            JSONObject jsonObjectVi = JSONUtil.parseObj(obj);

            try {
                // 获取parent对象
                JSONObject parent = jsonObjectVi.getJSONObject("parent");
                if (parent == null) {
                    parent = JSONUtil.createObj();
                    jsonObjectVi.set("parent", parent);
                }

                // 替换parent对象中的所有值
                parent.set("oid", partInfoVO.getOid().toString());
                parent.set("otype", map.get("OTYPE"));
                parent.set("name", map.get("NAME"));
                parent.set("viewID", map.get("VIEWID").toString());

                // 获取bomTreeNodeList数组
                JSONArray bomList = jsonObjectVi.getJSONArray("bomTreeNodeList");
                if (bomList == null) {
                    bomList = JSONUtil.createArray();
                    jsonObjectVi.set("bomTreeNodeList", bomList);
                }

                // 遍历bomTreeNodeList中的每个对象
                for (int j = 0; j < bomList.size(); j++) {
                    Object bomObj = bomList.get(j);
                    JSONObject bomNode = JSONUtil.parseObj(bomObj);

                    // 替换指定字段值
                    Map<String, Object> mapBOMNode = rtCfgBomMapper.selectParentByBomOidIn(partInfoVO.getPartNumber());
                    //todo 这里需要查询检入状态
                    //                    String oid = rtCfgBomMapper.selectOidByNumberOut(rtCfgBomDO.getMaterialcode());
                    //                    if(StrUtil.isNotEmpty(oid)){
                    //                        throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                    //                                "当前物料码【"+rtCfgBomDO.getMaterialcode()+"】为检出状态");
                    //                    }
                    String oid = String.valueOf(
                            typlmPdmPartService.queryLastPartDoByPartNumber(rtCfgBomDO.getMaterialcode()).getOid());
                    bomNode.set("mastername", rtCfgBomDO.getMaterialname());
                    bomNode.set("masterpartnumber", rtCfgBomDO.getMaterialcode());
                    bomNode.set("objOid", oid);
                    bomNode.set("objOtype", mapBOMNode.get("OTYPE"));
                    bomNode.set("parentPartName", map.get("NAME"));
                    bomNode.set("parentPartNumber", map.get("PARENTNUMBER"));
                    bomNode.set("partoid", oid);
                    bomNode.set("partotype", map.get("OTYPE"));

                    // 显式将修改后的对象放回数组
                    bomList.set(j, bomNode);
                }

                // 显式将修改后的对象放回数组
                jsonArray.set(i, jsonObjectVi);
            } catch (Exception e) {
                // 打印异常信息，便于排查问题
                e.printStackTrace();
            }
        }
        List<PartBomView> partBomViews = JSONUtil.toList(jsonArray, PartBomView.class);
        ResponseResult<Map<BigInteger, Long>> mapResponseResult = typlmBomController.saveBomViewListImmediately(
                partBomViews);
        if (MapUtil.isEmpty(mapResponseResult.getData())) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                    "成品BOM搭建子集物料数据异常【/rest/v1/bom/saveBomViewListImmediately接口】");
        }

    }

    private void saveBomViewListImmediatelyV2(String materialcode, String materialname, TyplmFolderObjDTO partInfoVO,
                                              Map<String, Object> map) {
        String jsonSaveBomViewListImmediately = "[{\"parent\":{\"oid\":\"734112810650025984\",\"otype\":\"ty.inteplm.part.CTyPart\",\"name\":\"名称1\",\"viewID\":\"323899843229581312\"},\"bomTreeNodeList\":[{\"oid\":\"\",\"partoid\":\"733666789905383424\",\"partotype\":\"ty.inteplm.part.CTyPart\",\"objOid\":\"733666789905383424\",\"objOtype\":\"ty.inteplm.part.CTyPart\",\"oriAreference\":\"\",\"oriAmount\":\"1\",\"amount\":\"1\",\"masterpartnumber\":\"18100-Z310110-0001\",\"mastername\":\"衍生物料码1\",\"parentPartNumber\":\"part202509061358042964939\",\"parentPartName\":\"名称1\",\"version\":\"A\",\"lifecyclestagekey\":\"Creating\",\"iterationid\":\"2\",\"value\":20,\"action\":\"add\",\"viewName\":\"Design\"}],\"addBOMFlag\":true}]";
        JSONArray jsonArray = JSONUtil.parseArray(jsonSaveBomViewListImmediately);

        // 遍历数组中的每个对象
        for (int i = 0; i < jsonArray.size(); i++) {
            Object obj = jsonArray.get(i);
            JSONObject jsonObjectVi = JSONUtil.parseObj(obj);

            try {
                // 获取parent对象
                JSONObject parent = jsonObjectVi.getJSONObject("parent");
                if (parent == null) {
                    parent = JSONUtil.createObj();
                    jsonObjectVi.set("parent", parent);
                }

                // 替换parent对象中的所有值
                parent.set("oid", partInfoVO.getOid().toString());
                parent.set("otype", map.get("OTYPE"));
                parent.set("name", map.get("NAME"));
                parent.set("viewID", map.get("VIEWID").toString());

                // 获取bomTreeNodeList数组
                JSONArray bomList = jsonObjectVi.getJSONArray("bomTreeNodeList");
                if (bomList == null) {
                    bomList = JSONUtil.createArray();
                    jsonObjectVi.set("bomTreeNodeList", bomList);
                }

                // 遍历bomTreeNodeList中的每个对象
                for (int j = 0; j < bomList.size(); j++) {
                    Object bomObj = bomList.get(j);
                    JSONObject bomNode = JSONUtil.parseObj(bomObj);

                    // 替换指定字段值
                    Map<String, Object> mapBOMNode = rtCfgBomMapper.selectParentByBomOidIn(materialcode);
                    String oid = rtCfgBomMapper.selectOidByNumberOut(materialcode);
                    if (StrUtil.isNotEmpty(oid)) {
                        throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                                "当前物料码【" + materialcode + "】为检出状态");
                    }
                    oid = rtCfgBomMapper.selectOidByNumberIn(materialcode);
                    bomNode.set("mastername", materialname);
                    bomNode.set("masterpartnumber", materialname);
                    bomNode.set("objOid", oid);
                    bomNode.set("objOtype", mapBOMNode.get("OTYPE"));
                    bomNode.set("parentPartName", map.get("NAME"));
                    bomNode.set("parentPartNumber", map.get("PARENTNUMBER"));
                    bomNode.set("partoid", oid);
                    bomNode.set("partotype", map.get("OTYPE"));

                    // 显式将修改后的对象放回数组
                    bomList.set(j, bomNode);
                }

                // 显式将修改后的对象放回数组
                jsonArray.set(i, jsonObjectVi);
            } catch (Exception e) {
                // 打印异常信息，便于排查问题
                e.printStackTrace();
            }
        }
        List<PartBomView> partBomViews = JSONUtil.toList(jsonArray, PartBomView.class);
        ResponseResult<Map<BigInteger, Long>> mapResponseResult = typlmBomController.saveBomViewListImmediately(
                partBomViews);
        if (MapUtil.isEmpty(mapResponseResult.getData())) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                    "成品BOM搭建子集物料数据异常【/rest/v1/bom/saveBomViewListImmediately接口】");
        }

    }

    private void bomAddBatchCheck(DspfMbomDetailDO rtCfgBomDO, PdmPartInfoVO partInfoVO, Map<String, Object> map) {
        String jsonBomAddBatchCheck = "{\"bomAddBatchCheckParentDTOList\":[{\"parentNumber\":\"part202509061358042964939\",\"parentMasterId\":\"734101118771773440\",\"parentViewName\":\"Design\",\"childList\":[{\"number\":\"18100-Z360110-0001\",\"masterId\":\"728682524089974784\",\"viewName\":\"Design\"}]}],\"isCheckView\":true,\"isCheckCircularReference\":true}";
        JSONObject jsonObject = JSONUtil.parseObj(jsonBomAddBatchCheck);

        // 获取bomAddBatchCheckParentDTOList数组
        JSONArray parentList = jsonObject.getJSONArray("bomAddBatchCheckParentDTOList");
        // 遍历父对象列表
        for (Object parentObj : parentList) {
            JSONObject parent = JSONUtil.parseObj(parentObj);

            // 修改父对象的相关字段
            parent.set("parentNumber", map.get("PARENTNUMBER").toString());
            parent.set("parentMasterId", map.get("PARENTMASTERID").toString());
            parent.set("parentViewName", "Design");

            // 获取子对象列表
            JSONArray childList = parent.getJSONArray("childList");

            // 遍历子对象列表
            for (Object childObj : childList) {
                JSONObject child = JSONUtil.parseObj(childObj);
                // 修改子对象的相关字段
                child.set("number", rtCfgBomDO.getMaterialcode());
                String masterId = rtCfgBomMapper.selectMasterIdByNumber(rtCfgBomDO.getMaterialcode());
                child.set("masterId", masterId);
                child.set("viewName", "Design");
            }
        }
        BomAddBatchCheckDTO bomAddBatchCheckDTO = JSONUtil.toBean(jsonObject.toStringPretty(),
                                                                  BomAddBatchCheckDTO.class);
        ResponseResult<Boolean> booleanResponseResult = typlmBomController.bomAddBatchCheck(bomAddBatchCheckDTO);
        if (!booleanResponseResult.getData()) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                    "成品BOM搭建子集物料数据异常【/rest/v1/bom/bomAddBatchCheck接口】");
        }
    }

    private void bomAddBatchCheckV2(String materialcode, Map<String, Object> map) {
        String jsonBomAddBatchCheck = "{\"bomAddBatchCheckParentDTOList\":[{\"parentNumber\":\"part202509061358042964939\",\"parentMasterId\":\"734101118771773440\",\"parentViewName\":\"Design\",\"childList\":[{\"number\":\"18100-Z360110-0001\",\"masterId\":\"728682524089974784\",\"viewName\":\"Design\"}]}],\"isCheckView\":true,\"isCheckCircularReference\":true}";
        JSONObject jsonObject = JSONUtil.parseObj(jsonBomAddBatchCheck);

        // 获取bomAddBatchCheckParentDTOList数组
        JSONArray parentList = jsonObject.getJSONArray("bomAddBatchCheckParentDTOList");
        // 遍历父对象列表
        for (Object parentObj : parentList) {
            JSONObject parent = JSONUtil.parseObj(parentObj);

            // 修改父对象的相关字段
            parent.set("parentNumber", map.get("PARENTNUMBER").toString());
            parent.set("parentMasterId", map.get("PARENTMASTERID").toString());
            parent.set("parentViewName", "Design");

            // 获取子对象列表
            JSONArray childList = parent.getJSONArray("childList");

            // 遍历子对象列表
            for (Object childObj : childList) {
                JSONObject child = JSONUtil.parseObj(childObj);
                // 修改子对象的相关字段
                child.set("number", materialcode);
                String masterId = rtCfgBomMapper.selectMasterIdByNumber(materialcode);
                child.set("masterId", masterId);
                child.set("viewName", "Design");
            }
        }
        BomAddBatchCheckDTO bomAddBatchCheckDTO = JSONUtil.toBean(jsonObject.toStringPretty(),
                                                                  BomAddBatchCheckDTO.class);
        ResponseResult<Boolean> booleanResponseResult = typlmBomController.bomAddBatchCheck(bomAddBatchCheckDTO);
        if (!booleanResponseResult.getData()) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                    "成品BOM搭建子集物料数据异常【/rest/v1/bom/bomAddBatchCheck接口】");
        }
    }


    /**
     * 调用底层接口进行父级BOM搭建
     *
     * @param rtCfgBomDO
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PdmPartInfoVO buildBOMParent(DspfMbomDetailDO rtCfgBomDO, String productCode,
                                        RtCfgStatusInfoDO rtCfgStatusInfoDO) {
        //        String jsonConfig = "{\"folderName\":\"成品BOM\",\"folderId\":\"734048728173330432\",\"folderPath\":\"/开发人员专用/成品BOM\",\"containerID\":\"707053057766981632\",\"containerType\":\"ty.inteplm.product.CTyPDMLinkProduct\",\"containerName\":\"开发人员专用\",\"productPath\":\"开发人员专用\",\"typeOid\":\"734033424986718208\",\"typeName\":\"成品BOM\",\"classId\":\"\",\"classDisplayName\":\"\",\"productID\":\"707053057766981632\",\"typeOType\":\"ty.inteplm.part.CTyPart|FinishedProductBOM\",\"lifecycleTemplate\":\"润通通用生命周期模板\",\"partNumber\":\"part202509061358042964939\",\"lifecycleTemplateID\":\"732949514087694336\",\"lifecycleTemplateName\":\"润通通用生命周期模板\",\"partView\":\"Design\",\"Stage\":\"阶段1\",\"BusinessEdition\":\"V1\",\"ChangeContent\":\"更改内容1\",\"number\":\"part202509061358042964939\",\"name\":\"名称1\",\"genericType\":\"standard\",\"category\":\"standard\",\"collapsible\":\"0\",\"enditem\":\"0\",\"description\":\"描述1\",\"assemblyMode\":\"component\",\"source\":\"Make\",\"unit\":\"PCS\",\"phantom\":\"0\",\"security\":\"非密\",\"securitylabels\":\"非密\",\"checkoutState\":\"\",\"lockdate\":\"\",\"lockeroName\":\"\",\"lifecycleMasterName\":\"润通通用生命周期模板\",\"lifecycleState\":\"Creating\",\"creatorName\":\"\",\"modifierName\":\"\",\"ownername\":\"\",\"creationTime\":\"\",\"updatecount\":\"\",\"lastupdatestampstr\":\"\",\"ibaAttribute\":{\"Stage\":[\"阶段1\"],\"BusinessEdition\":[\"V1\"],\"ChangeContent\":[\"更改内容1\"]}}";
        String jsonConfig183 = "{\"folderName\":\"成品码\",\"folderId\":\"715670121054076928\",\"folderPath\":\"/6-物料库/成品码\",\"containerID\":\"715669803838865408\",\"containerType\":\"ty.inteplm.product.CTyPDMLinkProduct\",\"containerName\":\"6-物料库\",\"productPath\":\"6-物料库\",\"typeOid\":\"726215360352518144\",\"typeName\":\"成品码\",\"classId\":\"752532820309819392\",\"classDisplayName\":\"电焊机\",\"productID\":\"715669803838865408\",\"typeOType\":\"ty.inteplm.part.CTyPart|ProductCode\",\"partView\":\"Design\",\"lifecycleTemplate\":\"润通通用生命周期模板\",\"partNumber\":\"CMP001\",\"lifecycleTemplateID\":\"751073324083789824\",\"lifecycleTemplateName\":\"润通通用生命周期模板\",\"00028\":\"历史创建时间\",\"Describe\":\"描述\",\"00020\":\"动力成品码\",\"00029\":\"历史停用时间\",\"00027\":\"历史创建人\",\"00030\":\"历史修改人\",\"00031\":\"历史修改时间\",\"00024\":\"结构件特征码\",\"00025\":\"成品特征码\",\"00022\":\"历史成品码\",\"NeedBatch\":\"2\",\"smallBatchQuantity\":\"100\",\"CertificationRequire\":\"无认证\",\"CustomerCode\":\"客户代码\",\"devCode\":\"\",\"application\":\"产品用途\",\"SegmNum\":\"B040\",\"factory\":[\"1200\"],\"developmentProject\":\"开发项目\",\"00035\":\"测试要求ID\",\"00033\":\"需求表ID\",\"00034\":\"需求变更编码\",\"00032\":\"分类ID\",\"00036\":\"认证要求ID\",\"00026\":\"成品码描述\",\"MOQ1\":\"最小起订量\",\"HalfBOM\":\"半BOM\",\"00023\":\"临时成品码\",\"00021\":\"标准化情况\",\"V2Model\":\"V2机型\",\"productType\":\"机型\",\"ModelMachine\":\"样机\",\"EBOMCode\":\"EBOM号\",\"TestRequire\":\"测试要求：空载：1900±50 功率：≥3.0/1800 怠速：800±150\",\"RecommendLevel\":\"推荐级别\",\"AgreeCretiYear\":\"同意认证年份\",\"CabinetType\":\"柜型\",\"SpecifyList\":\"指定列表\",\"StatusRequireCode\":\"状态需求编码\",\"PurchasedPower\":\"外购动力\",\"VerifyProductCode\":\"验证成品码\",\"PowerRegistrationModel\":\"动力备案机型\",\"reform\":\"改制\",\"AlreadyMassProduced\":\"已量产\",\"MechanicalEnvirCode\":\"机械环保代码\",\"OverallGoodsPallet\":\"整托加货物尺寸\",\"TrayMethod\":\"托盘方式\",\"VINCodeRule\":\"VIN码规则\",\"TerminalRegistrationModel\":\"终端备案机型\",\"MadeVietnam\":\"0\",\"RESTRICTEDDISPATCH\":\"限制派工\",\"00038\":\"零件分类\",\"number\":\"CMP001\",\"name\":\"测试成品码1\",\"collapsible\":\"0\",\"ibaAttribute\":{\"00028\":[\"历史创建时间\"],\"Describe\":[\"描述\"],\"00020\":[\"动力成品码\"],\"00029\":[\"历史停用时间\"],\"00027\":[\"历史创建人\"],\"00030\":[\"历史修改人\"],\"00031\":[\"历史修改时间\"],\"00024\":[\"结构件特征码\"],\"00025\":[\"成品特征码\"],\"00022\":[\"历史成品码\"],\"NeedBatch\":[\"2\"],\"smallBatchQuantity\":[\"100\"],\"CertificationRequire\":[\"无认证\"],\"CustomerCode\":[\"客户代码\"],\"devCode\":[\"\"],\"application\":[\"产品用途\"],\"SegmNum\":[\"B040\"],\"factory\":[\"1200\"],\"developmentProject\":[\"开发项目\"],\"00035\":[\"测试要求ID\"],\"00033\":[\"需求表ID\"],\"00034\":[\"需求变更编码\"],\"00032\":[\"分类ID\"],\"00036\":[\"认证要求ID\"],\"00026\":[\"成品码描述\"],\"MOQ1\":[\"最小起订量\"],\"HalfBOM\":[\"半BOM\"],\"00023\":[\"临时成品码\"],\"00021\":[\"标准化情况\"],\"V2Model\":[\"V2机型\"],\"productType\":[\"机型\"],\"ModelMachine\":[\"样机\"],\"EBOMCode\":[\"EBOM号\"],\"TestRequire\":[\"测试要求：空载：1900±50 功率：≥3.0/1800 怠速：800±150\"],\"RecommendLevel\":[\"推荐级别\"],\"AgreeCretiYear\":[\"同意认证年份\"],\"CabinetType\":[\"柜型\"],\"SpecifyList\":[\"指定列表\"],\"StatusRequireCode\":[\"状态需求编码\"],\"PurchasedPower\":[\"外购动力\"],\"VerifyProductCode\":[\"验证成品码\"],\"PowerRegistrationModel\":[\"动力备案机型\"],\"reform\":[\"改制\"],\"AlreadyMassProduced\":[\"已量产\"],\"MechanicalEnvirCode\":[\"机械环保代码\"],\"OverallGoodsPallet\":[\"整托加货物尺寸\"],\"TrayMethod\":[\"托盘方式\"],\"VINCodeRule\":[\"VIN码规则\"],\"TerminalRegistrationModel\":[\"终端备案机型\"],\"MadeVietnam\":[\"0\"],\"RESTRICTEDDISPATCH\":[\"限制派工\"],\"00038\":[\"零件分类\"]}}";
        InsertPartDTO insertPartDTO = JSONUtil.toBean(jsonConfig183, InsertPartDTO.class);
        DspfMbomBomDO dspfMbomBomDO = dspfMbomBomMapper.selectDspfMbomBomByBOMID(rtCfgBomDO.getBomid());


        LinkedHashMap<String, List<String>> ibaAttribute = new LinkedHashMap<>();
        //预留扩展属性字段添加
        ibaAttribute.put("productType", Arrays.asList(rtCfgStatusInfoDO.getProducttype()));//机型
        ibaAttribute.put("devCode", Arrays.asList(rtCfgStatusInfoDO.getDevcode()));//开发令
        ibaAttribute.put("00028", Arrays.asList(DateUtil.format(new Date(), "YYYY-MM-DD")));//创建历史时间
        ibaAttribute.put("Describe", Arrays.asList(dspfMbomBomDO.getBomdescr()));//描述
        ibaAttribute.put("00020", Arrays.asList(productCode));//动力成品码
        ibaAttribute.put("00027", Arrays.asList(TyAccountContext.getUser().getName()));//历史创建人
        ibaAttribute.put("00024", Arrays.asList(""));//结构件特征码*
        ibaAttribute.put("00025", Arrays.asList(""));//成品特征码*
        ibaAttribute.put("00022", Arrays.asList(dspfMbomBomDO.getOldmbomcode()));//历史成品码

        //获取限制派工的值
        PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(rtCfgStatusInfoDO.getEbomcode());
        String s = restrictedDispatchAOP.checkChildrenAndSetParentStatus(partDO);
        ibaAttribute.put("RESTRICTEDDISPATCH", Arrays.asList(s));//限制派工

        if (dspfMbomBomDO.getSmallbatch() != null) {
            ibaAttribute.put("NeedBatch",
                             Arrays.asList(String.valueOf(dspfMbomBomDO.getSmallbatch())));//是否需小批 0否 1是 2无需小批
        }
        if (dspfMbomBomDO.getSmallbatchamount() != null) {
            ibaAttribute.put("smallBatchQuantity",
                             Arrays.asList(String.valueOf(dspfMbomBomDO.getSmallbatchamount())));//小批数量
        }
        ibaAttribute.put("CertificationRequire", Arrays.asList(dspfMbomBomDO.getCertification()));//认证要求
        ibaAttribute.put("CustomerCode", Arrays.asList(dspfMbomBomDO.getClientcode()));//客户编码
        ibaAttribute.put("application", Arrays.asList(dspfMbomBomDO.getProductuse()));//产品用途
        ibaAttribute.put("SegmNum", Arrays.asList(""));//段号
        ibaAttribute.put("factory", Arrays.asList(dspfMbomBomDO.getFactory()));//工厂
        ibaAttribute.put("developmentProject", Arrays.asList(dspfMbomBomDO.getProjectcode()));//开发项目
        ibaAttribute.put("00035", Arrays.asList(dspfMbomBomDO.getTestingrequirements()));//测试要求id
        ibaAttribute.put("00033", Arrays.asList(dspfMbomBomDO.getStatusid()));//需求表id
        ibaAttribute.put("00034", Arrays.asList(""));//需求变更编码*
        ibaAttribute.put("00032", Arrays.asList(""));//分类id todo 需要进行创建分类然后将id带入
        ibaAttribute.put("00036", Arrays.asList(dspfMbomBomDO.getCertificationid()));//认证要求id
        ibaAttribute.put("00026", Arrays.asList(dspfMbomBomDO.getBomdescr()));//成品码描述
        if (dspfMbomBomDO.getMintrayload() != null) {
            ibaAttribute.put("MOQ1", Arrays.asList(String.valueOf(dspfMbomBomDO.getMintrayload())));//最小起订量
        }
        if (dspfMbomBomDO.getIshalfbom() != null) {
            ibaAttribute.put("HalfBOM", Arrays.asList(String.valueOf(dspfMbomBomDO.getIshalfbom())));//半BOM
        }
        if (dspfMbomBomDO.getTempcode() != null) {
            ibaAttribute.put("00023", Arrays.asList(String.valueOf(dspfMbomBomDO.getTempcode())));//临时成品码
        }
        ibaAttribute.put("00021", Arrays.asList(""));//标准化情况
        ibaAttribute.put("V2Model", Arrays.asList(""));//V2机型
        if (dspfMbomBomDO.getIsprototype() != null) {
            ibaAttribute.put("ModelMachine", Arrays.asList(String.valueOf(dspfMbomBomDO.getIsprototype())));//样机
        }
        ibaAttribute.put("EBOMCode", Arrays.asList(dspfMbomBomDO.getBarecode()));//EBOM号
        ibaAttribute.put("TestRequire", Arrays.asList(dspfMbomBomDO.getTestreqid()));//测试要求
        ibaAttribute.put("RecommendLevel", Arrays.asList(String.valueOf(dspfMbomBomDO.getPriority())));//推荐级别
        ibaAttribute.put("AgreeCretiYear", Arrays.asList(dspfMbomBomDO.getAgreeacceptrznf()));//同意认证年份
        ibaAttribute.put("CabinetType", Arrays.asList(""));//柜型*
        ibaAttribute.put("SpecifyList", Arrays.asList(""));//指定列表*
        ibaAttribute.put("StatusRequireCode", Arrays.asList(dspfMbomBomDO.getStatuscode()));//状态需求编码
        if (dspfMbomBomDO.getPurchasedpower() != null) {
            ibaAttribute.put("PurchasedPower", Arrays.asList(String.valueOf(dspfMbomBomDO.getPurchasedpower())));//外购动力
        }
        ibaAttribute.put("VerifyProductCode", Arrays.asList(dspfMbomBomDO.getProofmbomcode()));//验证成品码
        ibaAttribute.put("PowerRegistrationModel", Arrays.asList(dspfMbomBomDO.getDlrecordtype()));//动力备案机型
        if (dspfMbomBomDO.getRemanufacture() != null) {
            ibaAttribute.put("reform", Arrays.asList(String.valueOf(dspfMbomBomDO.getRemanufacture())));//改制
        }
        if (dspfMbomBomDO.getHasbatched() != null) {
            ibaAttribute.put("AlreadyMassProduced", Arrays.asList(String.valueOf(dspfMbomBomDO.getHasbatched())));//已量产
        }
        ibaAttribute.put("MechanicalEnvirCode", Arrays.asList(dspfMbomBomDO.getJxhbcode()));//机械环保代码
        ibaAttribute.put("OverallGoodsPallet", Arrays.asList(dspfMbomBomDO.getCargoDimensions()));//整托加货物尺寸
        ibaAttribute.put("TrayMethod", Arrays.asList(dspfMbomBomDO.getTraymode()));//托盘方式
        ibaAttribute.put("VINCodeRule", Arrays.asList(""));//VIN码规则
        ibaAttribute.put("TerminalRegistrationModel", Arrays.asList(dspfMbomBomDO.getZdrecordtype()));//终端备案机型
        if (dspfMbomBomDO.getIsvietnameseproduction() != null) {
            ibaAttribute.put("MadeVietnam",
                             Arrays.asList(String.valueOf(dspfMbomBomDO.getIsvietnameseproduction())));//越南生产
        }
        ibaAttribute.put("RESTRICTEDDISPATCH", Arrays.asList(""));//限制派工s
        ibaAttribute.put("00038", Arrays.asList(""));//零件分类

        insertPartDTO.setIbaAttribute(ibaAttribute);
        insertPartDTO.setName(dspfMbomBomDO.getBomdescr());
        insertPartDTO.setPartNumber(productCode);
        //        insertPartDTO.setClassId("");//分类id todo 从产品型谱分类带过来
        ArgumentUtils.checkArgumentNull(insertPartDTO.getPartView(),
                                        PartBomErrorCodeEnum.EXCEPTION_PARAM_VIEW_ID_IS_EMPTY.getLocaleMessage());
        PdmPartInfoVO partInfoVO = typlmPdmPartService.insertPart(new UploadFileDTO(), new LinkedHashMap<>(),
                                                                  insertPartDTO);
        List<CTyEntityBaseDO> updateList = new ArrayList();
        // 获取实体对象
        CTyEntityBaseDO entity = CommonUtil.getEntity(new IdentifierEntity(partInfoVO.getOid(), partInfoVO.getOtype()));

        // 将实体添加到待更新列表
        updateList.add(entity);
        if (IterUtil.isNotEmpty(updateList)) {
            // 批量更新生命周期状态
            this.typlmCommonLifecycleService.batchUpdateEntityLifecycle(updateList, "RELEASED", true, true);
        }
        //将成功搭建的bom编码存入BOM表头
        dspfMbomBomMapper.updateMbomCodeByBomid(productCode, rtCfgBomDO.getBomid());
        return partInfoVO;
    }

    @Transactional(rollbackFor = Exception.class)
    public PdmPartInfoVO buildBOMParentV2(DspfMbomDetailDO rtCfgBomDO, String productCode,
                                          RtCfgStatusInfoDO rtCfgStatusInfoDO) {
        String jsonConfig183 = "{\"folderName\":\"成品码\",\"folderId\":\"715670121054076928\",\"folderPath\":\"/6-物料库/成品码\",\"containerID\":\"715669803838865408\",\"containerType\":\"ty.inteplm.product.CTyPDMLinkProduct\",\"containerName\":\"6-物料库\",\"productPath\":\"6-物料库\",\"typeOid\":\"726215360352518144\",\"typeName\":\"成品码\",\"classId\":\"752532820309819392\",\"classDisplayName\":\"电焊机\",\"productID\":\"715669803838865408\",\"typeOType\":\"ty.inteplm.part.CTyPart|ProductCode\",\"partView\":\"Design\",\"lifecycleTemplate\":\"润通通用生命周期模板\",\"partNumber\":\"CMP001\",\"lifecycleTemplateID\":\"751073324083789824\",\"lifecycleTemplateName\":\"润通通用生命周期模板\",\"00028\":\"历史创建时间\",\"Describe\":\"描述\",\"00020\":\"动力成品码\",\"00029\":\"历史停用时间\",\"00027\":\"历史创建人\",\"00030\":\"历史修改人\",\"00031\":\"历史修改时间\",\"00024\":\"结构件特征码\",\"00025\":\"成品特征码\",\"00022\":\"历史成品码\",\"NeedBatch\":\"2\",\"smallBatchQuantity\":\"100\",\"CertificationRequire\":\"无认证\",\"CustomerCode\":\"客户代码\",\"devCode\":\"\",\"application\":\"产品用途\",\"SegmNum\":\"B040\",\"factory\":[\"1200\"],\"developmentProject\":\"开发项目\",\"00035\":\"测试要求ID\",\"00033\":\"需求表ID\",\"00034\":\"需求变更编码\",\"00032\":\"分类ID\",\"00036\":\"认证要求ID\",\"00026\":\"成品码描述\",\"MOQ1\":\"最小起订量\",\"HalfBOM\":\"半BOM\",\"00023\":\"临时成品码\",\"00021\":\"标准化情况\",\"V2Model\":\"V2机型\",\"productType\":\"机型\",\"ModelMachine\":\"样机\",\"EBOMCode\":\"EBOM号\",\"TestRequire\":\"测试要求：空载：1900±50 功率：≥3.0/1800 怠速：800±150\",\"RecommendLevel\":\"推荐级别\",\"AgreeCretiYear\":\"同意认证年份\",\"CabinetType\":\"柜型\",\"SpecifyList\":\"指定列表\",\"StatusRequireCode\":\"状态需求编码\",\"PurchasedPower\":\"外购动力\",\"VerifyProductCode\":\"验证成品码\",\"PowerRegistrationModel\":\"动力备案机型\",\"reform\":\"改制\",\"AlreadyMassProduced\":\"已量产\",\"MechanicalEnvirCode\":\"机械环保代码\",\"OverallGoodsPallet\":\"整托加货物尺寸\",\"TrayMethod\":\"托盘方式\",\"VINCodeRule\":\"VIN码规则\",\"TerminalRegistrationModel\":\"终端备案机型\",\"MadeVietnam\":\"0\",\"RESTRICTEDDISPATCH\":\"限制派工\",\"00038\":\"零件分类\",\"number\":\"CMP001\",\"name\":\"测试成品码1\",\"collapsible\":\"0\",\"ibaAttribute\":{\"00028\":[\"历史创建时间\"],\"Describe\":[\"描述\"],\"00020\":[\"动力成品码\"],\"00029\":[\"历史停用时间\"],\"00027\":[\"历史创建人\"],\"00030\":[\"历史修改人\"],\"00031\":[\"历史修改时间\"],\"00024\":[\"结构件特征码\"],\"00025\":[\"成品特征码\"],\"00022\":[\"历史成品码\"],\"NeedBatch\":[\"2\"],\"smallBatchQuantity\":[\"100\"],\"CertificationRequire\":[\"无认证\"],\"CustomerCode\":[\"客户代码\"],\"devCode\":[\"\"],\"application\":[\"产品用途\"],\"SegmNum\":[\"B040\"],\"factory\":[\"1200\"],\"developmentProject\":[\"开发项目\"],\"00035\":[\"测试要求ID\"],\"00033\":[\"需求表ID\"],\"00034\":[\"需求变更编码\"],\"00032\":[\"分类ID\"],\"00036\":[\"认证要求ID\"],\"00026\":[\"成品码描述\"],\"MOQ1\":[\"最小起订量\"],\"HalfBOM\":[\"半BOM\"],\"00023\":[\"临时成品码\"],\"00021\":[\"标准化情况\"],\"V2Model\":[\"V2机型\"],\"productType\":[\"机型\"],\"ModelMachine\":[\"样机\"],\"EBOMCode\":[\"EBOM号\"],\"TestRequire\":[\"测试要求：空载：1900±50 功率：≥3.0/1800 怠速：800±150\"],\"RecommendLevel\":[\"推荐级别\"],\"AgreeCretiYear\":[\"同意认证年份\"],\"CabinetType\":[\"柜型\"],\"SpecifyList\":[\"指定列表\"],\"StatusRequireCode\":[\"状态需求编码\"],\"PurchasedPower\":[\"外购动力\"],\"VerifyProductCode\":[\"验证成品码\"],\"PowerRegistrationModel\":[\"动力备案机型\"],\"reform\":[\"改制\"],\"AlreadyMassProduced\":[\"已量产\"],\"MechanicalEnvirCode\":[\"机械环保代码\"],\"OverallGoodsPallet\":[\"整托加货物尺寸\"],\"TrayMethod\":[\"托盘方式\"],\"VINCodeRule\":[\"VIN码规则\"],\"TerminalRegistrationModel\":[\"终端备案机型\"],\"MadeVietnam\":[\"0\"],\"RESTRICTEDDISPATCH\":[\"限制派工\"],\"00038\":[\"零件分类\"]}}";
        InsertPartDTO insertPartDTO = JSONUtil.toBean(jsonConfig183, InsertPartDTO.class);
        DspfMbomBomDO dspfMbomBomDO = dspfMbomBomMapper.selectDspfMbomBomByBOMID(rtCfgBomDO.getBomid());


        LinkedHashMap<String, List<String>> ibaAttribute = new LinkedHashMap<>();
        //预留扩展属性字段添加
        ibaAttribute.put("productType", Arrays.asList(rtCfgStatusInfoDO.getProducttype()));//机型
        ibaAttribute.put("devCode", Arrays.asList(rtCfgStatusInfoDO.getDevcode()));//开发令
        ibaAttribute.put("00028", Arrays.asList(DateUtil.format(new Date(), "YYYY-MM-DD")));//创建历史时间
        ibaAttribute.put("Describe", Arrays.asList(dspfMbomBomDO.getBomdescr()));//描述
        ibaAttribute.put("00020", Arrays.asList(productCode));//动力成品码
        ibaAttribute.put("00027", Arrays.asList(TyAccountContext.getUser().getName()));//历史创建人
        ibaAttribute.put("00024", Arrays.asList(""));//结构件特征码*
        ibaAttribute.put("00025", Arrays.asList(""));//成品特征码*
        ibaAttribute.put("00022", Arrays.asList(dspfMbomBomDO.getOldmbomcode()));//历史成品码

        //获取限制派工的值
        PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(rtCfgStatusInfoDO.getEbomcode());
        String s = restrictedDispatchAOP.checkChildrenAndSetParentStatus(partDO);
        ibaAttribute.put("RESTRICTEDDISPATCH", Arrays.asList(s));//限制派工

        if (dspfMbomBomDO.getSmallbatch() != null) {
            ibaAttribute.put("NeedBatch",
                             Arrays.asList(String.valueOf(dspfMbomBomDO.getSmallbatch())));//是否需小批 0否 1是 2无需小批
        }
        if (dspfMbomBomDO.getSmallbatchamount() != null) {
            ibaAttribute.put("smallBatchQuantity",
                             Arrays.asList(String.valueOf(dspfMbomBomDO.getSmallbatchamount())));//小批数量
        }
        ibaAttribute.put("CertificationRequire", Arrays.asList(dspfMbomBomDO.getCertification()));//认证要求
        ibaAttribute.put("CustomerCode", Arrays.asList(dspfMbomBomDO.getClientcode()));//客户编码
        ibaAttribute.put("application", Arrays.asList(dspfMbomBomDO.getProductuse()));//产品用途
        ibaAttribute.put("SegmNum", Arrays.asList(""));//段号
        ibaAttribute.put("factory", Arrays.asList(dspfMbomBomDO.getFactory()));//工厂
        ibaAttribute.put("developmentProject", Arrays.asList(dspfMbomBomDO.getProjectcode()));//开发项目
        ibaAttribute.put("00035", Arrays.asList(dspfMbomBomDO.getTestingrequirements()));//测试要求id
        ibaAttribute.put("00033", Arrays.asList(dspfMbomBomDO.getStatusid()));//需求表id
        ibaAttribute.put("00034", Arrays.asList(""));//需求变更编码*
        ibaAttribute.put("00032", Arrays.asList(""));//分类id todo 需要进行创建分类然后将id带入
        ibaAttribute.put("00036", Arrays.asList(dspfMbomBomDO.getCertificationid()));//认证要求id
        ibaAttribute.put("00026", Arrays.asList(dspfMbomBomDO.getBomdescr()));//成品码描述
        if (dspfMbomBomDO.getMintrayload() != null) {
            ibaAttribute.put("MOQ1", Arrays.asList(String.valueOf(dspfMbomBomDO.getMintrayload())));//最小起订量
        }
        if (dspfMbomBomDO.getIshalfbom() != null) {
            ibaAttribute.put("HalfBOM", Arrays.asList(String.valueOf(dspfMbomBomDO.getIshalfbom())));//半BOM
        }
        if (dspfMbomBomDO.getTempcode() != null) {
            ibaAttribute.put("00023", Arrays.asList(String.valueOf(dspfMbomBomDO.getTempcode())));//临时成品码
        }
        ibaAttribute.put("00021", Arrays.asList(""));//标准化情况
        ibaAttribute.put("V2Model", Arrays.asList(""));//V2机型
        if (dspfMbomBomDO.getIsprototype() != null) {
            ibaAttribute.put("ModelMachine", Arrays.asList(String.valueOf(dspfMbomBomDO.getIsprototype())));//样机
        }
        ibaAttribute.put("EBOMCode", Arrays.asList(dspfMbomBomDO.getBarecode()));//EBOM号
        ibaAttribute.put("TestRequire", Arrays.asList(dspfMbomBomDO.getTestreqid()));//测试要求
        ibaAttribute.put("RecommendLevel", Arrays.asList(String.valueOf(dspfMbomBomDO.getPriority())));//推荐级别
        ibaAttribute.put("AgreeCretiYear", Arrays.asList(dspfMbomBomDO.getAgreeacceptrznf()));//同意认证年份
        ibaAttribute.put("CabinetType", Arrays.asList(""));//柜型*
        ibaAttribute.put("SpecifyList", Arrays.asList(""));//指定列表*
        ibaAttribute.put("StatusRequireCode", Arrays.asList(dspfMbomBomDO.getStatuscode()));//状态需求编码
        if (dspfMbomBomDO.getPurchasedpower() != null) {
            ibaAttribute.put("PurchasedPower", Arrays.asList(String.valueOf(dspfMbomBomDO.getPurchasedpower())));//外购动力
        }
        ibaAttribute.put("VerifyProductCode", Arrays.asList(dspfMbomBomDO.getProofmbomcode()));//验证成品码
        ibaAttribute.put("PowerRegistrationModel", Arrays.asList(dspfMbomBomDO.getDlrecordtype()));//动力备案机型
        if (dspfMbomBomDO.getRemanufacture() != null) {
            ibaAttribute.put("reform", Arrays.asList(String.valueOf(dspfMbomBomDO.getRemanufacture())));//改制
        }
        if (dspfMbomBomDO.getHasbatched() != null) {
            ibaAttribute.put("AlreadyMassProduced", Arrays.asList(String.valueOf(dspfMbomBomDO.getHasbatched())));//已量产
        }
        ibaAttribute.put("MechanicalEnvirCode", Arrays.asList(dspfMbomBomDO.getJxhbcode()));//机械环保代码
        ibaAttribute.put("OverallGoodsPallet", Arrays.asList(dspfMbomBomDO.getCargoDimensions()));//整托加货物尺寸
        ibaAttribute.put("TrayMethod", Arrays.asList(dspfMbomBomDO.getTraymode()));//托盘方式
        ibaAttribute.put("VINCodeRule", Arrays.asList(""));//VIN码规则
        ibaAttribute.put("TerminalRegistrationModel", Arrays.asList(dspfMbomBomDO.getZdrecordtype()));//终端备案机型
        if (dspfMbomBomDO.getIsvietnameseproduction() != null) {
            ibaAttribute.put("MadeVietnam",
                             Arrays.asList(String.valueOf(dspfMbomBomDO.getIsvietnameseproduction())));//越南生产
        }
        ibaAttribute.put("RESTRICTEDDISPATCH", Arrays.asList(""));//限制派工s
        ibaAttribute.put("00038", Arrays.asList(""));//零件分类

        insertPartDTO.setIbaAttribute(ibaAttribute);
        insertPartDTO.setName(rtCfgStatusInfoDO.getProducttype());
        insertPartDTO.setPartNumber(productCode);
        //        insertPartDTO.setClassId("");//分类id todo 从产品型谱分类带过来
        ArgumentUtils.checkArgumentNull(insertPartDTO.getPartView(),
                                        PartBomErrorCodeEnum.EXCEPTION_PARAM_VIEW_ID_IS_EMPTY.getLocaleMessage());
        PdmPartInfoVO partInfoVO = typlmPdmPartService.insertPart(new UploadFileDTO(), new LinkedHashMap<>(),
                                                                  insertPartDTO);
        List<CTyEntityBaseDO> updateList = new ArrayList();
        // 获取实体对象
        CTyEntityBaseDO entity = CommonUtil.getEntity(new IdentifierEntity(partInfoVO.getOid(), partInfoVO.getOtype()));

        // 将实体添加到待更新列表
        updateList.add(entity);
        if (IterUtil.isNotEmpty(updateList)) {
            // 批量更新生命周期状态
            this.typlmCommonLifecycleService.batchUpdateEntityLifecycle(updateList, "RELEASED", true, true);
        }
        //将成功搭建的bom编码存入BOM表头
        dspfMbomBomMapper.updateMbomCodeByBomid(productCode, rtCfgBomDO.getBomid());
        return partInfoVO;
    }

    /**
     * 通过父级零部件oid生成相关工厂的试图
     *
     * @param
     */
    @Override
    public ResponseResult generateBOMToFactoryView(String partOid, String viewRefName, String viewDefOid) {

        try {
            //获取零部件详细信息
            TyPartAllVO tyPartAllVO = this.typlmPartService.queryPartAllVO(new BigInteger(partOid),
                                                                           "ty.inteplm.part.CTyPart");
            TyplmConvertBomInputDTO typlmConvertBomInputDTO = new TyplmConvertBomInputDTO();
            typlmConvertBomInputDTO.setTypeDefname(tyPartAllVO.getTypeName());//类型
            typlmConvertBomInputDTO.setViewName(viewRefName);//视图
            typlmConvertBomInputDTO.setOption("CopyPartstructureAndSpread");
            typlmConvertBomInputDTO.setOtype(TableTypeConstrant.TY_PART_OTYPE);
            typlmConvertBomInputDTO.setContainerOtype(tyPartAllVO.getContainerotype());
            typlmConvertBomInputDTO.setFolderPath(tyPartAllVO.getFolderPath());//文件夹路径
            typlmConvertBomInputDTO.setContainerName(tyPartAllVO.getContainerName());//零部件库
            typlmConvertBomInputDTO.setContainerOid(tyPartAllVO.getContaineroid());//零部件库oid
            typlmConvertBomInputDTO.setSubfolderOid(tyPartAllVO.getSubfolderoid());//文件夹Oid
            typlmConvertBomInputDTO.setViewDefOid(new BigInteger(viewDefOid));//工厂视图Oid
            typlmConvertBomInputDTO.setOid(tyPartAllVO.getOid());//物料Oid
            ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = buildExpandBomTreeByFilterDTO(tyPartAllVO.getOid() + "",
                                                                                              viewRefName,
                                                                                              tyPartAllVO
                                                                                                      .getObjectNumber(),
                                                                                              false, true);//PBom
            typlmConvertBomInputDTO.setExpandBomTreeByFilterDTO(expandBomTreeByFilterDTO);
            typlmConvertBomInputDTO.setCreateType("createBranch");

            Map<String, PartBomTreeByFilterVO> result = this.typlmPartBomService.bomStructurePreview(
                    typlmConvertBomInputDTO);
            PartDetailsVO downStreamBom = createDownStreamBom(result, viewRefName, new BigInteger(viewDefOid));
            return ResponseResult.success(downStreamBom);
        } catch (Exception e) {
            log.error("生成工厂视图异常", e);
            return ResponseResult.fail("500", "生成工厂视图异常");
        }
    }

    @Override
    public ResponseResult manualAdjustmentOfGroupPowerStructure(RtCfgBomDTO rtCfgBomDTO) {
        if (rtCfgBomDTO == null) {
            return ResponseResult.fail("500", "参数为空");
        }
        int i = rtCfgBomMapper.manualAdjustmentOfGroupPowerStructure(rtCfgBomDTO);
        if (i <= 0) {
            throw new RuntimeException("手动调整组功率结构失败");
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult getWorkFlowName(String templateName) {
        Example example = new Example(WorkFlow.class, true, true);
        example.createCriteria().andEqualTo("name", templateName);
        List<WorkFlow> workFlowList = this.typlmWorkFlowService.simpleQueryListByExample(example);
        if (ObjectUtils.isEmpty(workFlowList)) {
            throw RTErrorCodeEnum.NOT_FOUND_OBJECT_WORK_FLOW_TEMPLATE.getException();
        }
        WorkFlow workFlow = workFlowList.get(0);
        OptionalParticipantUserTaskVO optionalParticipantUserTaskVO = this.typlmWorkFlowContainerService
                .getOptionalParticipantUserTaskVO(null,
                                                  workFlow.getOid(),
                                                  null,
                                                  null,
                                                  BigInteger.valueOf(
                                                          0),
                                                  null);
        //        List<UserTaskDTO> allUserTask = typlmWorkFlowContainerService.getAllUserTask(workFlow.getOid(), workFlow.getContainerOid(), workFlow.getContainerOtype());


        return ResponseResult.success(optionalParticipantUserTaskVO);
    }

    @Override
    public ResponseResult replacePartNumber(String partNumber, String oid, String producttype) {
        // 参数校验
        if (partNumber == null || oid == null) {
            return ResponseResult.success();
        }
        try {
            // 获取模板编码
            String templateCode = dspfMbomDetailMapper.getTemplateCode(oid);
            if (templateCode == null) {
                return ResponseResult.success();
            }
            List<RtCfgMzVO> rtCfgMzVOS = dspfMbomDetailMapper.selectBytemplateCode(templateCode);
            if (rtCfgMzVOS == null || rtCfgMzVOS.isEmpty()) {
                return ResponseResult.success();
            }
            // 截取零件号的前5位字符
            String replace = partNumber.substring(0, 5);
            StringBuilder contentResult = new StringBuilder();
            for (RtCfgMzVO rtCfgMzVO : rtCfgMzVOS) {
                if (StrUtil.isNotBlank(rtCfgMzVO.getProducttype())){
                    if (!rtCfgMzVO.getProducttype().equals(producttype)){
                        continue;
                    }
                    String partslist = rtCfgMzVO.getPartslist();
                    switch (rtCfgMzVO.getNeedtemcode()) {
                        case "0":
                            StringBuilder partBomTreeByFilter = getPartBomTreeByFilter(partslist,partNumber);
                            contentResult.append(partBomTreeByFilter);
                            break;
                        case "1":
                            StringBuilder partBomTreeByFilter1 = getPartBomTreeByFilter(partslist,partNumber);
                            contentResult.append(partBomTreeByFilter1);
                            break;
                        case "2":
                            StringBuilder partBomTreeByFilter2 = getPartBomTreeByFilter(partslist,replace);
                            contentResult.append(partBomTreeByFilter2);
                            break;
                        default:
                            return ResponseResult.success();
                    }
                }else {
                    String partslist = rtCfgMzVO.getPartslist();
                    switch (rtCfgMzVO.getNeedtemcode()) {
                        case "0":
                            StringBuilder partBomTreeByFilter = getPartBomTreeByFilter(partslist,partNumber);
                            contentResult.append(partBomTreeByFilter);
                            break;
                        case "1":
                            StringBuilder partBomTreeByFilter1 = getPartBomTreeByFilter(partslist,partNumber);
                            contentResult.append(partBomTreeByFilter1);
                            break;
                        case "2":
                            StringBuilder partBomTreeByFilter2 = getPartBomTreeByFilter(partslist,replace);
                            contentResult.append(partBomTreeByFilter2);
                            break;
                        default:
                            return ResponseResult.success();
                    }
                }

            }
            return ResponseResult.success(contentResult.toString());
        } catch (Exception e) {
            e.printStackTrace();
            // 异常处理
            return ResponseResult.fail("500", "处理过程中发生错误 ");
        }
    }

    public  StringBuilder getPartBomTreeByFilter(String partslist, String replace) {
        StringBuilder contentResult = new StringBuilder();
        if (StrUtil.isNotBlank(partslist)) {
            // 解析JSON数组
            JSONArray jsonArray = JSONUtil.parseArray(partslist);
            List<Map<String, Object>> parts = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                parts.add(jsonObject.toBean(Map.class));
            }
            // 遍历查找匹配的code
            for (Map<String, Object> part : parts) {
                Object codeObj = part.get("code");
                if (codeObj != null && replace.equals(codeObj.toString())) {
                    // 找到匹配项，获取content
                    Object contentObj = part.get("displayName");
                    if (contentObj != null) {
                        if (contentResult.length() > 0) {
                            contentResult.append(",");
                        }
                        contentResult.append(contentObj.toString());
                    }
                }
            }
        }
        return contentResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult saveBOM(List<DspfMbomBomDTO> dtos) {
        /*
         *   BOM保存逻辑
         *    1.将用户调整后的BOM结构提交保存到BOM表头、表体中
         * */
        if (IterUtil.isEmpty(dtos)) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                    "BOM结构参数为空，请先确认");
        }

        for (int i = 0; i < dtos.size(); i++) {
            DspfMbomBomDO dspfMbomBomDO = dtos.get(i).getDspfMbomBomDO();
            if (StrUtil.isNotEmpty(dspfMbomBomDO.getBomid())) {
                dspfMbomBomMapper.deleteDspfMbomBomByBOMID(dspfMbomBomDO.getBomid());
            }
            boolean flag = false;

            //当前如果填写了验证成品码 则验证小批
            if (StrUtil.isNotEmpty(dspfMbomBomDO.getProofmbomcode())) {
                //通过验证成品码 找到该成品码的验证成品码
                String currentProofBomCode = dspfMbomBomDO.getProofmbomcode();
                //最终结果
                MbomVO resultMbom = new MbomVO();
                //通过验证成品码查询成品码 循环查询直到mbomcode为空
                while (StrUtil.isNotEmpty(currentProofBomCode)) {
                    MbomVO mbomVO = dspfMbomBomMapper.selectMbomcodeByProofmbomcode(currentProofBomCode);
                    if (mbomVO == null) {
                        break;
                    }
                    // 如果当前mbomVO的验证码为空，则是我们要找的结果
                    if (StrUtil.isEmpty(mbomVO.getProofmbomcode())) {
                        resultMbom = mbomVO;
                        break;
                    }
                    // 更新currentProofBomCode为下一个proofmbomcode
                    currentProofBomCode = mbomVO.getProofmbomcode();
                }
                if (resultMbom.getSmallbatch() != null) {
                    dspfMbomBomDO.setProofmbomcode(resultMbom.getMbomcode());
                    flag = true;
                }

            }

            dspfMbomBomMapper.insertDspfMbomBom(dspfMbomBomDO);
            List<DspfMbomDetailDO> mbomDetailDOList = dtos.get(i).getMbomDetailDOList();
            if (IterUtil.isNotEmpty(mbomDetailDOList)) {
                mbomDetailDOList.stream().forEach(k -> {
                    if (StrUtil.isNotEmpty(k.getKid())) {
                        dspfMbomDetailMapper.deleteDspfMbomDetailByKID(k.getKid());
                    }
                    k.setFCreatedate(new Date());
                    k.setFCreateusername(TyAccountContext.getUser().getName());
                    if(StrUtil.isEmpty(k.getKid())){
                        k.setKid(snowflakeIdComponent.getInstance().nextId().toString());
                    }
                    dspfMbomDetailMapper.insertDspfMbomDetail(k);
                });
            }
            if (flag) {
                String str = "";
                if (dspfMbomBomDO.getSmallbatch() == 0) {
                    str = "验证成品码为" + dspfMbomBomDO.getMbomcode() + ",小批属性为：否";
                } else if (dspfMbomBomDO.getSmallbatch() == 1) {
                    str = "验证成品码为" + dspfMbomBomDO.getMbomcode() + ",小批属性为：是";
                } else if (dspfMbomBomDO.getSmallbatch() == 2) {
                    str = "验证成品码为" + dspfMbomBomDO.getMbomcode() + ",小批属性为：无需小批";
                }
                return ResponseResult.success(str);
            }
        }
        return ResponseResult.success("保存成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult importExcel(MultipartFile file, String bomid) throws Exception {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);  // 设置表头的行数（默认是1，表头在文件的第一行）
        params.setSheetNum(1);  // 设置需要导入的工作表（默认是第一个工作表）
        params.setTitleRows(1); // 设置表格标题的行数，如果有的话
        List<DspfMbomDetailPoiDTO> dataList = ExcelImportUtil.importExcel(file.getInputStream(),
                                                                          DspfMbomDetailPoiDTO.class, params);
        dataList.stream().forEach(i -> {
            /*
             * 导入校验逻辑
             *   1.检查物料图号是否在系统中存在
             *   2.校验图号扩展属性:制造属性是否为直采P、自制M
             *   3.校验图号是否为售后件、失效件
             *   //制造属性字母对应数字 P(1)、X(2)、C(3)、M(4)、A(5)、S(6)
             * */


            Integer in = dspfMbomDetailMapper.selectIbaByNumber(i.getMaterialcode());
            if (in.intValue() == 0) {
                throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                        "当前图号/物料码【" + i.getMaterialcode() + "】在系统中不存在");
            }

            Integer pm = dspfMbomDetailMapper.selectIbaByPm(i.getMaterialcode());
            if (pm.intValue() == 0) {
                throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                        "当前图号/物料码【" + i.getMaterialcode() + "】在系统中制造属性不为直采P、自制M");
            }

            Integer s = dspfMbomDetailMapper.selectIbaBys(i.getMaterialcode());
            if (s.intValue() > 0) {
                throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                        "当前图号/物料码【" + i.getMaterialcode() + "】在系统中为售后件");
            }
            List<PartMasterDO> partMasterDOS = typlmPartService.queryPartMasterByPartNumber(i.getMaterialcode());
            PartMasterDO partMasterDO = partMasterDOS.get(0);
            PartDetailsVO partDetailsVO = typlmPartService.queryPartDetails(partMasterDO.getOid(),
                                                                            partMasterDO.getOtype());
            String lifecycleState = partDetailsVO.getLifecycleState();
            if (!"已发布".equals(lifecycleState)) {
                throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                        "物料【" + i.getMaterialcode() + "】不是已发布状态，请确认");
            }

            DspfMbomDetailDO dspfMbomDetailDO = BeanUtil.copyProperties(i, DspfMbomDetailDO.class);
            dspfMbomDetailDO.setBomid(bomid);
            dspfMbomDetailDO.setKid(String.valueOf(snowflakeIdComponent.getInstance().nextId()));
            dspfMbomDetailMapper.insertDspfMbomDetail(dspfMbomDetailDO);

        });
        return ResponseResult.success("导入成功");
    }

    private void typlmCodeIn(DspfMbomBomDO dspfMbomBomDO, TyplmFolderObjDTO typlmFolderObjDTO) {
        CommonIteratorVO commonIteratorVO = new CommonIteratorVO();
        commonIteratorVO.setId(String.valueOf(typlmFolderObjDTO.getOid()));
        commonIteratorVO.setTypeDefName(typlmFolderObjDTO.getCadType());
        ResponseResult<List<BusinessObjectVO>> listResponseResult = typlmIterationController.batchCheckIn(
                Arrays.asList(commonIteratorVO));
        if (!"SUCCESS".equals(listResponseResult.getResult())) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("【" + dspfMbomBomDO + "】检入失败");
        }

    }

    private void typlmBomAdd(DspfMbomBomDO dspfMbomBomDO, TyplmFolderObjDTO typlmFolderObjDTO,
                             List<DspfMbomDetailDO> mbomDetailDOList) {
        String mbomcode = dspfMbomBomDO.getMbomcode();
        String otype = dspfMbomBomDO.getOtype();
        if (StrUtil.isEmpty(otype)) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("成品码【" + mbomcode + "】还未定义（终端/动力/传动）类型");
        }

        List<DspfMbomDetailDO> filteredList = mbomDetailDOList.stream()
                .filter(item -> otype.equals(item.getOtype()))
                .filter(item -> dspfMbomBomDO.getBomid().equals(item.getBomid()))
                .collect(Collectors.toList());
        if (IterUtil.isEmpty(filteredList)) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("成品码【" + mbomcode + "】没有添加的子项物料数据");
        }

        //根据成品BOM编码查询出parentNumber、parentMasterId、parentViewName字段
        Map<String, Object> map = rtCfgBomMapper.selectParentByBomOidIn(typlmFolderObjDTO.getObjectNumber());
        String oid = rtCfgBomMapper.selectOidByNumberOut(typlmFolderObjDTO.getObjectNumber());
        if (StrUtil.isNotEmpty(oid)) {
            throw RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException(
                    "当前物料码【" + typlmFolderObjDTO.getObjectNumber() + "】为检出状态");
        }
        filteredList.stream().forEach(i -> {
            //子级搭建
            this.bomAddBatchCheckV2(i.getMaterialcode(), map);
            this.saveBomViewListImmediatelyV2(i.getMaterialcode(), i.getMaterialname(), typlmFolderObjDTO, map);
        });

    }


    public ExpandBomTreeByFilterDTO buildExpandBomTreeByFilterDTO(String partOid, String viewName, String number,
                                                                  boolean isNestedTree, boolean isUp) {
        ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new ExpandBomTreeByFilterDTO();
        expandBomTreeByFilterDTO.setFatherOid(partOid);
        expandBomTreeByFilterDTO.setFatherOtype(TableTypeConstrant.TY_PART_OTYPE);
        expandBomTreeByFilterDTO.setFatherNumber(number);
        //        expandBomTreeByFilterDTO.setFatherMasterOid(String.valueOf(partDO.getMasteredoid()));
        expandBomTreeByFilterDTO.setExpandLevel("1");
        expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
        expandBomTreeByFilterDTO.setIsQueryIBA(true);
        expandBomTreeByFilterDTO.setIsNestedTree(isNestedTree);
        if (isUp) {
            expandBomTreeByFilterDTO.setIsUp(true);
        }
        List<ChildPartsFiltersDTO> conditions = new ArrayList<>();
        ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
        childPartsFiltersDTO.setView(viewName);
        childPartsFiltersDTO.setExpandCondition("latest");
        conditions.add(childPartsFiltersDTO);
        expandBomTreeByFilterDTO.setConditions(conditions);
        return expandBomTreeByFilterDTO;
    }

    private PartDetailsVO createDownStreamBom(Map<String, PartBomTreeByFilterVO> result, String viewName,
                                              BigInteger viewDefOid) {
        Set<String> keySet = result.keySet();
        PartDetailsVO downStreamBom = new PartDetailsVO();
        for (String key : keySet) {
            PartBomTreeByFilterVO partBomTreeByFilterVO = result.get(key);
            List<PartBomTree> partBomTreeList = partBomTreeByFilterVO.getPartBomTreeList();
            BatchSaveAsDTO batchSaveAsDTO = new BatchSaveAsDTO();
            List<BomSaveAsDTO> bomSaveAsList = new ArrayList<>();
            for (PartBomTree partBomTree : partBomTreeList) {
                if ("0".equals(partBomTree.getLevel())) {
                    batchSaveAsDTO.setOid(new BigInteger(partBomTree.getPartoid()));
                }
                String typeName = partBomTree.getTypeName();
                BomSaveAsDTO bomSaveAsDTO = new BomSaveAsDTO();
                bomSaveAsDTO.setPartOid(new BigInteger(partBomTree.getPartoid()));
                if (partBomTree.getAoid() != null) {
                    bomSaveAsDTO.setParentPartOid(partBomTree.getAoid());
                }
                bomSaveAsDTO.setPartMasterOid(new BigInteger(partBomTree.getMasteredoid()));
                bomSaveAsDTO.setPartNumber(partBomTree.getObjectNumber());
                bomSaveAsDTO.setName(partBomTree.getName());
                if (partBomTree.getIsExist()) {
                    bomSaveAsDTO.setViewId(typlmViewDefService.queryViewByName("Design").get(0).getOid());
                    bomSaveAsDTO.setViewName("Design");
                } else {
                    bomSaveAsDTO.setViewId(viewDefOid);
                    bomSaveAsDTO.setViewName(viewName);
                }
                bomSaveAsDTO.setContainerOid(partBomTree.getContainerOid());//容器ID
                bomSaveAsDTO.setContainerOtype(partBomTree.getContainerOtype());//容器类型
                bomSaveAsDTO.setSubfolderoid(partBomTree.getFolderoid());//文件夹ID
                bomSaveAsDTO.setOptype(false);
                if (partBomTree.getOid() == null) {
                    bomSaveAsDTO.setPartUsagelinkOid(new BigInteger("0"));
                } else {
                    bomSaveAsDTO.setPartUsagelinkOid(partBomTree.getOid());
                }
                bomSaveAsDTO.setTypeName(typeName);
                bomSaveAsDTO.setTypeOid(partBomTree.getPartTypeOid());
                bomSaveAsList.add(bomSaveAsDTO);
            }
            ExpandBomTreeByFilterDTO filterDto = new ExpandBomTreeByFilterDTO();
            List<ChildPartsFiltersDTO> conditions = new ArrayList<>();
            ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
            childPartsFiltersDTO.setView("Design");
            childPartsFiltersDTO.setExpandCondition("latest");
            conditions.add(childPartsFiltersDTO);
            filterDto.setExpandLevel("N");
            filterDto.setGiveUsesOccurrence("N");
            filterDto.setIsUp(false);
            filterDto.setIsQueryIBA(null);
            filterDto.setConditions(conditions);
            batchSaveAsDTO.setBomSaveAsList(bomSaveAsList);
            batchSaveAsDTO.setFilterDto(filterDto);
            downStreamBom = this.typlmPartBomService.createDownStreamBom(
                    batchSaveAsDTO);//createNewDownStreamPart

        }
        return downStreamBom;
    }

}




